What is the correct way to declare and use a enum variable, in Javascript?
Like this (using the example of various AI states for an AI State Machine):
enum AIState { Asleep, Idling, Chasing, Fleeing, HavingLunch }
And then you can assign any value from that enum to a variable, like this:
var state = AIState.Idling;
In the above example, the variable's type is implicitly defined as "AIState". You can explicitly define a variable with that type like this:
var state : AIState;
And similarly you can define the input parameter of a function to recieve a value from your enum, like this:
function PerformAction( currentState : AIState ) {
switch (currentState) {
case AIState.Asleep:
Debug.Log("Zzzz.");
break;
// etc...
}
}
You can also assign values to your individual enum elements.
enum Layer
{
Protagonists = 9,
Antagonists = 10,
HeadsUpDisplay = 11,
LevelBoundaries = 13
}
This is incredibly helpful if you use layers, for example. Rather than using
this.gameObject.layer = 9;
You could instead use the easier to read
this.gameObject.layer = Layer.Protagonists;
This is especially helpful as there is then only one location, your enum, where you have to change the layer number if a change is needed.