Best solution for the AI to mimic waiting?

Trying to find the best solution to have my AI to mimic a player. Right now a player would go to the store and buy new inventory items which takes time. The computer does it in a fraction of a second and then returns control to the player. I want to delay that a few seconds. I thought I was clever using StartCouroutine() but that seemed to set it on a separate thread and then continues processing the next line, which sends it back to the openStoreAITurn(). I am wondering how other people perform intentional waiting to give the AI a more human response?

There were 3 separate things that happened that I want spaced out every 2 seconds and this did not work. I thought at first the Coroutine waited but it seems to send it off on a different thread and continues to process.

void someMethod(){
       StartCoroutine(openStoreAITurn(1)); 
       StartCoroutine(openStoreAITurn(2));
       StartCoroutine(openStoreAITurn(3));
}

IEnumerator openStoreAITurn(int num){
     yield return new WaitForSeconds(2f);
        if (num == 1) {
            // perform first action
        }
        if (num == 2) {
            // perform actions
        }
        if (num == 3) {
            // perform last action
        }
    }

Coroutines aren’t on a separate thread, your method that calls them does not block while they run. Just have the coroutine wait the few seconds and set something that the rest of your code looks for to see if the AI should move on to the next step. Or you could do that all with accumulating timers in Update. Depends on how complex you want to make this.

Thanks, I took a different approach and it worked to delay each step 2 seconds using the coroutines still.

    IEnumerator openStoreAITurn(){
        yield return new WaitForSeconds(2f);
            // do something here
        yield return new WaitForSeconds(2f);
            // do something here
        yield return new WaitForSeconds(2f);
            // do something here
    }

Just adding to this, if you wanted each store action to wait 2 seconds, I could suggest that you simply lay them out in order in 1 coroutine (rather than 3), and add a yield wait for seconds in between each action (if that’s what you had in mind).:slight_smile:
After that, as mentioned, keep track that they’re busy. Perhaps by setting a variable at the beginning of the coroutine and updating at the end, when it’s all over.

Nice, your post came in 2 seconds before I finished writing :slight_smile:

1 Like

I had a feeling you were going to suggest this approach anyway, so I went for it! :slight_smile: