loop animation through controller for period of time? C#

Hi everyone!

I’m only learning unity and C# so go easy on me :slight_smile:

Ive managed to set off an animation trigger using the lines of code below:

int runHash = Animator.StringToHash("Run");

void Start(){
anim = GetComponent<Animator>();
anim.SetTrigger (runHash);
}

But how would i have the animation loop for a certain number of times or length of time? Is there a way to do that in C# using some sort of variable or do i have to make that animation a default through code?

Any insight or code would i would be appreciative of.

Thanks guys! :slight_smile:

So the usual way to use the Animator is to send a trigger that takes it to another state when that change needs to happen. If that’s after a certain amount of time, you simply use a coroutine.

Say that you’ve got the code above, and want to switch to the walk anim after five seconds, you do:

private Animator anim;

void Start() {
    anim = GetComponent<Animator>();
    anim.SetTrigger ("Run");
    StartCoroutine(ChangeAnim());
}

IEnumerator ChangeAnim() {
    yield return new WaitForSeconds(5f);
    anim.SetTrigger("Walk");
}

Note that you don’t have to store the hash, just sending in the name of the trigger you’re using works.

Now, normally you’d change between a running and walking animation depending on how fast your character is moving;

anim.SetFloat("Speed", rigidbody.velocity.mangitude);

And simply set your animator to switch between walking and running when the Speed variable crosses a certain treshhold.