really weird problem, Enum refusing to change state.

Ok, so I’m using a simple enum and case/switch to control the State of my enemy AI. It’s all up and running fine, except for when I’m trying to change to AIState.dying from the AIState.injured.

Having said that, I can change to AIState.dying from other states, and can change from AIState.injured to other states with no problem at all. The problem is only when changing from AIState.injured to AIState.dying.

I’ve included some, (messy) code below to illustrate the problem.

My enum is set up like this:

enum AIState
{
spawning,
roaming,
attacking,
injured,
chasing,
dying
}

Then I switch between states like this:

switch (currentState) {
        case AIState.spawning: 
        
            yield WaitForSeconds (1);
            currentState = AIState.roaming;
            
            break;
 
        case AIState.roaming: 
            //make enemy roam around
            
            //checking for proximity to player here
            distance = Vector3.Distance( player.transform.position, transform.position);
		
				if ( distance < 1.8 && distance > 0.05 ) 
				{
					currentState = AIState.chasing;	
				}
            
            break;
            etc

The state giving me problems is like so:

     case AIState.injured: 
			            myHealth --;
			            
			            if (myHealth <= 0)
			            {
						Debug.Log("health = 0.");
				     	currentState = AIState.dying; //<-- problem is here
			            }

                        currentState = AIState.roaming;
    
    break;

And the dying state is here:

case AIState.dying: 
            Debug.Log("dying.");
            Destroy (gameObject);
            
            break;

Now, if I set: currentState = AIState.dying; from another state, it works fine. the enemy is deleted and “dying” is printed to the console.

Likewise, if I change the conditional statement in the problem state to:

if (myHealth <= 0)
    			            {
    						Debug.Log("health = 0.");
    				     	currentState = AIState.attacking; //<-- or another AIState    			            }

Then again, it works perfectly. The problem is only when changing from injured to dying.

Apologies for the terrible formatting. The problem is pretty straightforward, but it’s tough to explain using snippets of code. I’m not precious about my code, if anyone wants the whole enemy script, just say so.

Does anyone know what’s causing this strange behaviour?

Thanks

Dan

At line 10 you seem to set the value back straight after changing to dying.

if (myHealth <= 0)
{
	Debug.Log("health = 0.");
	currentState = AIState.dying; //<-- problem is here
}
 
currentState = AIState.roaming; // LOOK HERE! You set it back straight after setting it to dying. It never stood a chance.