Why use enum in javascript and how it works.?
I saw some code which use enum at unity-javascript.
Why use enum in javascript and how it works.?
I saw some code which use enum at unity-javascript.
You use enums to avoid magic numbers Magic number (programming) - Wikipedia, to avoid “an unnamed or ill-documented numerical constant value”.
enum Commands {patroll, stay, run};
var command : Commands = Commands.stay;
function Update()
{
if (Input.GetKey("p"))
{
command = Commands.patroll;
}
// ...
switch (command)
{
case Commands.stay:
print("Stay state");
break;
case Commands.patroll:
print("Patroll state");
break;
case Commands.run:
print("Run state");
break;
default:
print("No command");
break;
}
}
You could associate stay to 0, patroll to 1 and Run to 2, but it makes your code clearer if you use enums.
Thanks~~
I also like them because you get a nice drop-down picker in the Editor.
Yup, what Jesse said. The one caveat I’d add is that although they convert between int and enum pretty nicely, things get a little bit hairy if you have to concatenate arrays of them as strings… that conversion takes them into the named string representation of the enum and not their base integer index. Like say, for example, saving an array of CSV enums or enums in JSON to PlayerPrefs. You’ll probably never run into that issue, but it’ll save you time to know it exists. ![]()