- Home /
How to use Enum?
Hi all,
I've been searching around, and I haven't been able to find any guides on using enums in Unity.
I was wondering if someone could show me how to use them in an 'if' statement.
This is my code so far:
#pragma strict
var moveSpeed = 5;
enum Direction {up,down,left,right,none};
var moveDirection : Direction;
function Update () {
if (moveDirection = moveDirection.up) {
transform.eulerAngles = Vector3.zero;
MoveForward();
}
if (moveDirection = moveDirection.down) {
transform.eulerAngles = Vector3.zero;
transform.rotation.z = 90;
MoveForward();
}
if (moveDirection = moveDirection.left) {
transform.eulerAngles = Vector3.zero;
transform.rotation.z = 180;
MoveForward();
}
if (moveDirection = moveDirection.right) {
transform.eulerAngles = Vector3.zero;
transform.rotation.z = 270;
MoveForward();
}
}
function MoveForward () {
transform.Translate(Vector3.forward);
}
And I get 3 errors:
Assets/Scripts/MyGameScripts/Gameplay/Movement/PlayerMovementController.js(22,27): BCE0044: expecting ), found '='.
Assets/Scripts/MyGameScripts/Gameplay/Movement/PlayerMovementController.js(22,45): BCE0043: Unexpected token: ).
Assets/Scripts/MyGameScripts/Gameplay/Movement/PlayerMovementController.js(23,39): BCE0044: expecting :, found '='.
How can I fix this, and so you know any guides on using enums? Thanks!
By the way why not using Vector3?
var moveDirection :Vector3;
if(moveDirection == Vector3.right){}
if(moveDirection == Vector3.up){}
// and so on
The problem with this approach is that moveDirection
won't be exactly equal to right or up (depends on how it is calculated). So if you want to use something like this, then the workable solution is if( ( moveDirection - Vector3.right ).sqr$$anonymous$$agnitude < threshold ) {}
with some low threshold
like 0.1f. Though it is worse performance-wise because you have to compare vectors and not just int's.
It would depend how the value is passed. Since he uses the enum it is either right or left or forward or ...but never in between. So it means he would passing:
moveDirection = Vector3.up;
So there is no inacuracy in that case
You can't compare the enum value (i.e. int
) to the Vector3
, the compiler will report a syntax error.
Ok one last time and then I stop,
var moveDirection :Vector3;
if(moveDirection == Vector3.right){}
if(moveDirection == Vector3.up){}
// and so on
moveDirection is a Vector3. But ok I give you credit, enum is faster.
Answer by moonstruck · Jul 11, 2013 at 11:58 AM
First of all, if you want to compare then you should use operator == and NOT the assignment operator. Then the enum values don't belong to the variable, but to the object. So you can rewrite it as following:
if (moveDirection == Direction.up) {
// ...
}