Search Unity

Enum & Switch

Discussion in 'Scripting' started by Cooper37, Oct 2, 2014.

  1. Cooper37

    Cooper37

    Joined:
    Jul 21, 2012
    Posts:
    383
    Can someone explain why I'm getting an error by the "switch" statement, and why it spawns a "Debug" game object when I select Trigger from the menu?
    Code (csharp):
    1.  
    2. enum nodes{debug,trigger};
    3.  
    4.     function Menu(){
    5.         var menu : GenericMenu = new GenericMenu();
    6.         menu.AddItem(new GUIContent("Events/Debug/Debug.Log"),false,Nodes,nodes.debug);
    7.        
    8.         menu.AddItem(new GUIContent("Conditions/Trigger"),false,Nodes,nodes.trigger);
    9.             menu.ShowAsContext();  
    10.     }
    11.  
    12.     function Nodes(obj : Object){
    13.      Debug.Log ("Selected: " + obj);
    14.         switch(obj){
    15.             case nodes.debug:
    16.                 var debug = new GameObject("Debug");
    17.             break;
    18.            
    19.             case nodes.trigger:
    20.                 var trigger = new GameObject("Trigger");
    21.             break;
    22.         }
    23.     }
    24.  
     
  2. fffMalzbier

    fffMalzbier

    Joined:
    Jun 14, 2011
    Posts:
    3,276
    How about giving out what the actual error massage is?
    That way we can probably help you.
     
  3. cranky

    cranky

    Joined:
    Jun 11, 2014
    Posts:
    180
    I'm not too familiar with UnityScript, but it looks like "obj" is being typed as a Unity Object when it should be System.Object.

    Change Object to object (lowercase O) in this line "function Nodes(obj :Object){"
     
  4. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    You may need to cast. You shouldn't be making your parameter "object" anyway if you know it's going to be an enum.. Enumerations are value types and by passing it as "Object" it will be assumed to be a reference type. So, when you pass your enum into the method it will be "boxed" as the type object and then "unboxed" back into your enumeration in your method. This will cause allocations and feed the garbage collector. Instead do:

    Code (csharp):
    1.  
    2. function Nodes(obj : nodes){
    3.  
    That will also solve your switch issue.
     
  5. Cooper37

    Cooper37

    Joined:
    Jul 21, 2012
    Posts:
    383
    Oh, I see what you mean! Thank you, that solved it :)