Search Unity

Question Is it possible to use an array in a switch?

Discussion in 'Scripting' started by KaiserApple, Sep 26, 2022.

  1. KaiserApple

    KaiserApple

    Joined:
    Sep 12, 2021
    Posts:
    31
    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:
    Code (CSharp):
    1. public int health;
    2.     GameObject name;
    3.     GameObject[] type;
    4.     void Start()
    5.     {
    6.         name = gameObject;
    7.         if(name = type[0])
    8.         {
    9.             health = 25;
    10.         }
    11.         if(name = type[1])
    12.         {
    13.             health = 35;
    14.         }
    15.         if(name = type[2])
    16.         {
    17.             health = 72;
    18.         }
    19.         if(name = type[3])
    20.         {
    21.             health = 9;
    22.         }
    23.         if(name = type[4])
    24.         {
    25.             health = 50;
    26.         }
    27.         if(name = type[5])
    28.         {
    29.             health = 1000;
    30.         }
    31. //...and so on
    32.  
    33.     }
    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.
     
  2. Terraya

    Terraya

    Joined:
    Mar 8, 2018
    Posts:
    646
    use an for or forEach loop ;)
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    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!!
     
  4. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    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.
     
    Bunny83, AnimalMan and Kurt-Dekker like this.