- Home /
Question by
will_brett · Mar 30, 2014 at 11:37 PM ·
animationwait
Wait Random time then play animation
Hey everyone,
Hoping this is a simple one but its got me stumped.
Im making a simple 2d games and I want my characters to blink occasionally. So I need to create a sprite animation and then have the animator wait a random amount of time and then play the blink animation.
What I've tried so far is making a blink animation and then created this script to play the animation however this did not work
public class WaitAndPlayAnim : MonoBehaviour {
public float randomWait;
void Start()
{
StartCoroutine ("WaitSeconds"); //wait random seconds for animation
}
IEnumerator WaitSeconds ()
{
while(true)
{
var randomWait = Random.Range(0, 6);
Debug.Log ("wait " + randomWait + " Seconds");
animation.Play("Blink");
yield return new WaitForSeconds(randomWait);
}
}
}
Comment
Answer by Sanky · May 27, 2015 at 07:25 AM
He try this code its work for me... Comment if occurred any issue
bool playAnim = true; // var for boolean
void Update(){
if (playAnim)
StartCoroutine(WaitAnim()); //wait random seconds for animation
}
public IEnumerator WaitAnim()
{
playAnim = false;
int randomWait = Random.Range(0, 10);
print ("Time" + randomWait + " Play"); //debug
yield return new WaitForSeconds(randomWait);
animation.Play("Blink");; //Put your animation string
playAnim = true;
}
Answer by NCartist · Apr 07, 2018 at 11:42 PM
I had to modify this code to get it to work in Unity 2017. This code worked for me.
public IEnumerator WaitAnim()
{
playAnim = false;
int randomWait = Random.Range(0, 5);
print("Time" + randomWait + " Play"); //debug
yield return new WaitForSeconds(randomWait);
anim.Play("Blink", -1, 0f); //Put your animation string
playAnim = true;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613141548im_/https://answers.unity.com/themes/thub/images/avi.jpg)