- Home /
loop animation through controller for period of time? C#
Hi everyone!
I'm only learning unity and C# so go easy on me :)
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! :)
Answer by Baste · Dec 01, 2014 at 10:19 AM
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.
Thank you so much Baste for your detailed response, it's so good to see people who are happy to share their knowledge without giving cryptic answers!
Your suggestion is great and has really helped me but I'm still a bit stuck.
the character is a non-playable character so the first code you gave me suites well but how can i make the Run animation keep running and not just do one cycle?
You're awesome thank you again!
Cheers
You need to set the animation to loop in the animation itself.
If it's a standalone animation clip, you just select it and check the "loop time" right on top of the inspector.
If the animation's a part of an imported .fbx or blender file or something similar, you open the animation tab on the file, find the animation, and check the box that says "loop time".
You need to do this for every animation you're going to use that needs to loop.
O$$anonymous$$G! Baste you are amazing! Thank you so much for all your help! That worked a treat! For all those other people reading who have had this trouble, I used what Baste used above but set a bool variable and changed that to true to make it work!
Ahhhh!! All the excites!! :P
Your answer
Follow this Question
Related Questions
Transition Animations at end of current loop 0 Answers
Animation method/coroutine playable once or loop 0 Answers
Animation keeps playing 2 Answers
Distribute terrain in zones 3 Answers