How can I simplify this long series of if statements?

I use Unity to create a game. I have several animal enemies in the game.

I work on missions inside the game that you need to kill a random number of random animals, I already have this.

I have a problem with increasing the number of missions when you kill an animal.

I have a script (dead) sitting on every animal, when the animal dies, it calls a public function inside a dead script.

From a dead script, it should increase the int value in the "MissionHolder" script, where all animals have an int value, which increases when you kill the animal.

The problem is that I don’t know which animal kills when a player kills an animal, what I did:

public string Name; public MissionHolder missionHolder; public void Kill() { if (name == "Tiger") { missionHolder.Tiger += 1; } if (name == "Hyena") { missionHolder.Hyena += 1; } if (name == "Gorilla") { missionHolder.Gorilla += 1; } if (name == "Giraffe") { missionHolder.Giraffe += 1; } if (name == "Gazelle") { missionHolder.Gazelle += 1; } 

and etc.

Now I call each animal its own name in a dead script, but it is not very effective.

Does anyone know a better way to do this?

+7
performance c # unity3d
source share
1 answer

You can use Dictionary . Register all animal types as a string, then use Action as the value in the Start or Awake function. This Action will contain all the names that you have in your if . If you want to kill an animal, check to see if it is in this Dictionary , then do Action .

 public string Name; public MissionHolder missionHolder; Dictionary<string, Action> animalToAction = new Dictionary<string, Action>(); void Start() { //Register and animal type and Action animalToAction.Add("Tiger", delegate { missionHolder.Tiger += 1; }); animalToAction.Add("Hyena", delegate { missionHolder.Hyena += 1; }); animalToAction.Add("Gorilla", delegate { missionHolder.Gorilla += 1; }); animalToAction.Add("Giraffe", delegate { missionHolder.Giraffe += 1; }); animalToAction.Add("Gazelle", delegate { missionHolder.Gazelle += 1; }); } 

Your new Kill feature:

 public void Kill() { //If the name exists in the dictionary, execute the corresponding delegate Action action; if (animalToAction.TryGetValue(Name, out action)) { //Execute the approprite code action(); } } 

You can use EventManager , but this is optional.

+8
source share

All Articles