Is it possible to use an array in a switch?

Hello.
I want to make a script that can see how much health an enemy has, depending of the prefab. This can work fine with conditions, but I don’t want to look at something ugly like this:

public int health;
    GameObject name;
    GameObject[] type;
    void Start()
    {
        name = gameObject;
        if(name = type[0])
        {
            health = 25;
        }
        if(name = type[1])
        {
            health = 35;
        }
        if(name = type[2])
        {
            health = 72;
        }
        if(name = type[3])
        {
            health = 9;
        }
        if(name = type[4])
        {
            health = 50;
        }
        if(name = type[5])
        {
            health = 1000;
        }
//...and so on

    }

Instead, I wanted to create something like a switch, however I can’t access the number between the square brackets with the switch, and I want to find a way to not use the method shown above. Thanks.

use an for or forEach loop :wink:

There’s a lot of problems here… you may wish to reconsider:

Don’t use name. It’s a property of Unity.Object already.

Don’t use type… it’s just a horribly useless name.

Don’t confuse yourself (or people reading your code) any more than necessary.

Single equal is assign. You want double equal to compare.

These will all fail to work mysteriously because you are assigning a GameObject into a GameObject. A GameObject can be viewed as a bool… so any non-destroyed GameObject will return true for ALL of the above if() statements.

Good Lord, just put the health IN the prefab!!

5 Likes

You seem to be comparing the name to some types, likely your prefabs, and then return a hardcoded health value. Why cant you dynamically look up the health value of whatsever prefab you are considering at the time? It would be saved somewhere on there, right? Maybe explain what it is you actually need to do.

3 Likes