Make animations happen at random times C#

I have a couple of animations which I want to be run at random times…
At the moment, I run the animations on click…
After the user clicks, I choose a random number using Random.Range and then, depending on the number chosen by the function, I run one of the animations. I need help to run the animations randomly in time and to make them so that they won’t interrupt each other… I know the time of each animation.

I actually looked up on the older posts and found nothing helpful… I tried something with WaitForSeconds, but it ran one animation per frame…

Can someone help me? (C#)

2 Likes

I’ve been wondering about this as well and I was considering making a thread on it, would appreciate an answer on this too.

I would still like your help on this problem guys, so please answer… An idea, anything that might be useful will be of big help to me!

In a coroutine, play a random animation, wait for the animation to complete, wait a random amount of time, repeat.

You need to create a animation controller that contains state for each of these random animations. It will also need a transition state from where it can transition in to these random animations. To specify which animation you’ll also need to add integer animation parameter called for example RandomIndex.

Then you need to create transitions from the transition state to all the random transition states and add condition RandomIndex equals number of the animation. Then you simply need to modify this index through the code.

Make sure these random animation states also transition back to the transition (no conditions, exit time only). I have placed the RandomAnimationDone to the PickRandomAnim state in the picture.

You can also use AnimationStateBehaviors to tell when the animation/state is done.

using UnityEngine;

public class PlayRandomAnim : MonoBehaviour
{
    public Animator anim;
    int randomAnim = Animator.StringToHash("RandomIndex");
    bool animationDone = true;

    void Start()
    {
        RandomDelay();
    }
 
    void RandomDelay()
    {
        float delay = Random.Range(1.0f, 5.0f);
        Invoke("PickRandomAnim", delay);
    }
  
    public void PickRandomAnim()
    {
        if(animationDone)
        {
            anim.SetInteger(randomAnim, Random.Range(1, 4));
            animationDone = false;
        }
    }
 
    //called from AnimStateBehavior
    public void RandomAnimationDone()
    {
        anim.SetInteger(randomAnim, -1);
        animationDone = true;
        RandomDelay();
    }
}
using UnityEngine;

public class RandomAnimationDone : StateMachineBehaviour
{
    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        PlayRandomAnim r = animator.gameObject.GetComponent<PlayRandomAnim>();
        if (r)
            r.RandomAnimationDone();
    }
}

1 Like