I have a character controller which I adapted to fit my own character, and as it is, there is only a single idle animation that plays in loop when my character is not moving. However I would like at least two to play, at random intervals, just to mix it up a bit.
I created a parameter in the Animator called RandomIdle, as an integer, which I change randomly in the code as follows using Update():
private void Update()
{
StartCoroutine("IdleChanger");
}
IEnumerator IdleChanger()
{
randomIdle = Random.Range(0, 10);
yield return new WaitForSeconds(3);
anim.SetInteger("RandomIdle", randomIdle);
}
My thought process was that I would play IDLE02 when the randomIdle integer is greater than 5 otherwise play the IDLE01 instead. But even though my WaitForSeconds is inbetween the resetting of the variable randomIdle and then assigning it to the parameter, it just changes instantly, continuously. Which doesn’t really work well.
Can anyone help me figure out why the WaitForSeconds isn’t doing what I’m expecting it to do?
Hello there, welcome
Please read this page for how you can post code that shows up nicely on the forums: Using code tags properly
I think this solution might work for you…
void Start() {
StartCoroutine(IdleChanger());
}
IEnumerator IdleChanger() {
// cached wait for seconds variable for subsequent use.
WaitForSeconds wfs = new WaitForSeconds(3);
while (true) {
yield return wfs;
// random integer range of 0, 10 gives 0 -> 9
anim.SetInteger("RandomIdle", Random.Range(0, 10));
}
}
This will randomly change the animation (assuming your animator is setup correctly) every 3 seconds. Or at least pass a different random value every 3 seconds, and you have your different idles… however that is
Please delete the StartCoroutine from Update lol That will make a new coroutine every frame. You do not want that.
If Update() is empty after you delete that, delete the entire update method from the code, too
Hope that helps.
Hi, thanks for the quick response. Have edited the post now to make the code look better! I was looking for a button in the editor, but couldn’t find it
Yes, that has fixed it. I think my problem was having it in Update(). I only have a FixedUpdate() in there so I deleted the Update() after moving the Coroutine to the Start() function. As you can probably tell, I’m still a bit new to the coding side of Unity!
Thanks again
Michael
It’s all good. We all start somewhere.
Enjoy