Search Unity

  1. We are migrating the Unity Forums to Unity Discussions by the end of July. Read our announcement for more information and let us know if you have any questions.
    Dismiss Notice
  2. Dismiss Notice

Question Trying to pass an unknown enum type

Discussion in 'Scripting' started by valmarus, Aug 19, 2020.

  1. valmarus

    valmarus

    Joined:
    May 19, 2017
    Posts:
    3
    I'm trying to pass around an unknown enum type which is set by switch cases then automatically generate arrays from them. Given that the following, which I use in other areas of code, works:

    Code (CSharp):
    1. subType = new EquipmentSubTypeList[Enum.GetNames(typeof(EQUIPMENTTYPE)).Length];
    I tried the following which doesn't:

    Code (CSharp):
    1. Type enumType;
    2.  
    3.         switch (equipmentType)
    4.         {
    5.             case EQUIPMENTTYPE.Weapon:
    6.                 enumType = typeof(WEAPONTYPE);
    7.                 break;
    8.         }
    9.  
    10.         if (subType == null || subType.Length < 1)
    11.         {
    12.             subType = new EquipmentSubTypeList[Enum.GetNames(enumType).Length];
    13.         }
    GetNames(enumType) is where I am getting the error in VS. I can't figure out why this isn't working. Any help with why it doesn't and any advice for achieving what I am trying to would be greatly appreciated.
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    What is the error you are getting? That enumType is uninitialized? If equipmentType is not EQUIPMENTTYPE.Weapon then you never set enumType before using it.
     
  3. valmarus

    valmarus

    Joined:
    May 19, 2017
    Posts:
    3
    You're right, I'm an idiot, the error is being thrown because there's no default case and it could theoretically be unassigned by the time it gets there even though in practice it couldn't possibly be (i trimmed away all the other cases to avoid bloating the snippet). Guess I can solve that by wrapping the if in another if to make sure it's an enum type to get rid of the error. Thanks!
     
  4. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    When you switch on an enum, you should always have a "default" case. Someone could come along and add new values to the enum. Someone could even cast an integer into your enum type to get a value that doesn't correspond to any of your named values.

    It's possible the default case will just throw an exception, but you should have one.
     
    PraetorBlue likes this.