Dionysos Sjaak
Dionysos Sjaak

Reputation: 105

How can I simplify this long series of if statements?

I'm using Unity to make a game. I have multiple animal enemies in the game.

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

What I have a problem with is to increase the mission count when you kill an animal.

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

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

The problem is I don't know which animal gets killed when the player kills a animal, what I did is this:

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;
    }

etc.

Now I just name each animal by its name on the dead script but this is not really efficient.

Does anyone knows a better way to do this?

Upvotes: 7

Views: 235

Answers (1)

Programmer
Programmer

Reputation: 125305

You can use Dictionary. Register all the animal types as a string then use Action as the value in the Start or Awake function. That Action will contain all the names you currently have in your if statements. When you want to kill an animal, check if it is in that Dictionary then execute the 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 function:

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 to do this but it's not necessary.

Upvotes: 8

Related Questions