How do I add a delay in a switch statement?

    float distance = Vector3.Distance(transform.position, player.position);
var State = distance > 10 ? AIState.TowardsPlayer : AIState.Right;
Debug.Log(distance);

switch (State)
{
case AIState.TowardsPlayer:
transform.LookAt(player.transform);
transform.position += transform.forward * approaching * Time.deltaTime;
break;
case AIState.Right:
transform.position += transform.right * 1f * Time.deltaTime;
Invoke("AIState.TowardsPlayer", 2f);
break;


I want it to have a slight delay after AIState.Right finishes its execution before moving onto AIState.TowardsPlayer. I put Invoke but it didn't work.

• Don't forget to show us the context where this code is running. It makes a big difference whether this is happening in Start, Update, a collision handler, or a Coroutine, etc. Be detailed: "it didn't work" is never enough information to diagnose a problem. What outcome did you expect to observe? How did the actual observed outcome differ from this? – DMGregory Jul 29 at 14:54

You're trying to add a delay like this:

Invoke("AIState.TowardsPlayer", 2f);


This does not work because AIState.TowardsPlayer is an enum value. Invoke() is used to call functions.

You probably want to use a coroutine, something like this:

private IEnumerator UpdateState() {
while (true) {
float distance = Vector3.Distance(transform.position, player.position);
var state = distance > 10 ? AIState.TowardsPlayer : AIState.Right;

switch (state) {
case AIState.TowardsPlayer:
transform.LookAt(player.transform);
transform.position += transform.forward * approaching * Time.deltaTime;
break;
case AIState.Right:
transform.position += transform.right * 1f * Time.deltaTime;
yield return new WaitForSeconds(2f);
break;
}

//wait one frame before next loop iteration, so we never hang the application
//in an infinite loop
yield return null;
}
}

void OnEnable() {
}


Here we have a yield return new WaitForSeconds(2f); statement to pause for two seconds after the AIState.Right condition occurs.

If you're not familiar with Coroutines, make sure to read up on them, as they can make your life a lot easier.