- Home /
Problems with enums and switches (C#)
I'm working on my enemy AI here. What I'm trying to do is something similar to the standard character controller, where it just has a current character state enum, but what I'm doing with it is have a switch for said enum where it tells it what animation to play.
using UnityEngine;
using System.Collections;
enum EnemyState{IDLE = 0, WALK = 1, RUN = 2, ATTACK = 3, KILL = 4};
public class EnemyBehavior : MonoBehaviour
{
public AnimationClip enemyIdle;//setting animations
public AnimationClip enemyWalk;//walking
public AnimationClip enemyRun;//running/chasing
public AnimationClip enemyAttack;//attacking player
public AnimationClip enemyKill;//killing player
public Transform Player;//adds the player to the script
public int WalkingSpeed = 1;//sets the normal walking speed
public int RunningSpeed = 3;//sets the running (chase player) speed
public int MaxDist= 15;//maximum distance the player can be before enemy stops chasing the player
public int MinDist= 7;//how close the player can be to enemy for enemy to start chasing player
EnemyState currentState;
void Update()//when object enters the Sphere Collider (Chase Range)
{
if(Vector3.Distance(transform.position,Player.position) <= MaxDist)//if that object has the tag "Player"
{
transform.LookAt(Player);//Looks at the player
currentState = EnemyState.RUN;
transform.position += transform.forward*RunningSpeed*Time.deltaTime;//follows the player
}else if(Vector3.Distance(transform.position,Player.position) >= MaxDist)
{
RoamAround ();
}
switch (currentState)
{
case IDLE:
animation.Play ("enemyIdle");
break;
case WALK:
animation.Play ("enemyWalk");
break;
case RUN:
animation.Play ("enemyRun");
break;
case ATTACK:
animation.Play ("enemyAttack");
break;
case KILL:
animation.Play ("enemyKill");
break;
default:
animation.Play ("enemyIdle");
break;
}
}
void RoamAround()
{
currentState = EnemyState.IDLE;
}
}
What I'm getting is errors like "The name `IDLE' does not exist in the current context" for every single EnemyState. What am I doing wrong? (I've tried adding the enum into the class, but it doesn't work like that either.)
Okay, never $$anonymous$$d. Apparently I needed to add "EnemyState." before everything in the switch.
Answer by morbidcamel · Jan 15, 2014 at 06:07 AM
In C# you have to put the Enum name as part of the qualifier:
switch(currentState)
{
case EnemyState.IDLE:
...
break;
}
You also might want to move you enum back into the class or add "public" in front of it. I suggest going through a few scripting tutorials.
Answer by ammirea · Sep 02, 2019 at 04:12 PM
Make EnemyState
public and put it inside EnemyBehaviour
and write using static EnemyBehaviour.EnemyState;
at the top of the script. This only works with DotNet 4.x +
Your answer
Follow this Question
Related Questions
Problem with my weapons switch statement C# 3 Answers
Changing enum values 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers