Delay an animation

How can I get an Animator to play a specific state after a certain time using IEnumerator:

using UnityEngine;
using System.Collections;

public class StateDelay : MonoBehaviour {

    IEnumerator Start()
    {
        yield return new WaitForSeconds(3f);

       ?   ?   ?   ?   ?
    }
}

I have a GameObject within a Scene, that has an Animator and an animation state within it. The animation doesn’t play automatically cause I’ve created an Empty State and placed it as Default. The animation state needs to be called upon. I can do that with the button OnClick function, but I am not clicking anything in this case, I want it appear ‘by itself’ after a certain time you enter the Scene. I would attach the script to the Scene Main Camera. Just don’t know how to call for an Animator to play a State via code.

Thanx.

Start is a set function of the Unity engine so you shouldn’t change it to IEnumerator like that. You want to create a seperate IEnumerator method that you call using StartCoRoutine. Your start method would kick that process off.

Can you write an example of that code… when you find time :smile:

I’ll be home in a few hours and whip you something up. I could probably do it off the top of my head but no doubt i’d mess up a small detail and it wont work. Its handy to draw from working examples i have in projects at home lol

Great :wink:

public void Start() {
     StartCoroutine(playAnimation);
}

public IEnumerator playAnimation() {
     yield return new WaitForSeconds(3f);

     // Insert your Play Animations here

}
1 Like

I’ll test it out it in a bit, and report.

But how do I call an animation state from the animator? I don’t even know that code. I only know the name of the state that I want.

I’ve found it on the web :smile:. It works fine now. Thanks for the help.

1 Like

Oh ok, this will get a bit more complicated. You can create an animator variable and assign the component to it. That will let you call the trigger you should have set up in your animator component in the Unity Editor.
It will be something like:

// Add this in your variables at the top of your object script
private Animator animator;                  //Used to store a reference to the Player's animator component.

// Put this line of code in your Start method for your object
animator = GetComponent<Animator>();

// Use this line of code to set a trigger in your animation section:
animator.SetTrigger("playerAttack");  // Change playerAttack to whatever trigger you are using
2 Likes