Search Unity

Enum problem can't equal to string.

Discussion in 'Scripting' started by alienx2, Mar 31, 2011.

  1. alienx2

    alienx2

    Joined:
    Nov 19, 2010
    Posts:
    40
    Hi anyone, im in trouble with between Enum and IF. here code below:

    Code (csharp):
    1.  
    2. enum CurrPlayer { NONE, Player1, Player2, Player3, Player4 }
    3.  
    4. static var CurrentPlayer : CurrPlayer = NONE;
    5.  
    6. function Update() {
    7. if(CurrentPlayer == this.gameObject.tag)
    8. {
    9. [INDENT]do action...[/INDENT]
    10. }
    11.  
    Error:
    Code (csharp):
    1. BCE0051: Operator '==' cannot be used with a left hand side of type 'CurrPlayer' and a right hand side of type 'String'.
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    The correct syntax for using an enum is

    Code (csharp):
    1. static var currentPlayer = CurrPlayer.NONE;
    In any case, you can use ToString() to convert an enum to a string value.

    --Eric
     
  3. alienx2

    alienx2

    Joined:
    Nov 19, 2010
    Posts:
    40
    Wow it works. i use ToString()... Thanks, Sir Eric ^_^
     
  4. Antony-Blackett

    Antony-Blackett

    Joined:
    Feb 15, 2011
    Posts:
    1,778
    You can also go the other way by doing something like

    C#
    Code (csharp):
    1. EnumType enumValue = System.Enum.Parse(EnumType, stringEnumValue) as EnumType;
     
  5. alienx2

    alienx2

    Joined:
    Nov 19, 2010
    Posts:
    40
    Is there way convert to Javascript? can't?
     
  6. Antony-Blackett

    Antony-Blackett

    Joined:
    Feb 15, 2011
    Posts:
    1,778
    Ummm, I'm not to familiar with Javascript... but at a guess it'd be something like this.

    untested:
    Code (csharp):
    1. var enumValue : EnumType = System.Enum.Parse( EnumType, stringEnumValue );
    Someone correct me if I'm wrong.
     
  7. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    You're not wrong, but if you're using #pragma strict, you'd also have to use #pragma downcast. Doing "System.Enum.Parse( EnumType, stringEnumValue ) as EnumType;" won't work because it's a value type, not a reference type. Actually I don't think your C# code would work. It should be:

    Code (csharp):
    1. EnumType enumValue = (EnumType)System.Enum.Parse(typeof(EnumType), stringEnumValue);
    --Eric
     
  8. kilik128

    kilik128

    Joined:
    Jul 15, 2013
    Posts:
    909
    not working for me anymore something change in c# ?
     
  9. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Nothing changed and it works fine.

    --Eric