How to randomly start & stop an animation?

I’m fairly new to Unity (and C#). At the moment I’m trying to make a simple 2D platformer.

I have some items in my game that the player can collect for points. I have a very simple animation for those items (it’s a diamond that shines). But, I don’t want to have all the diamonds keep shining and shining. I want them to shine and then wait a random amount of time before they shine again.

I tried something with two animations (an idle state and a shining state) and I also googled a bit here and there and read about some other things. I just can’t get it to work.

It’s not the first time I have problems with the animator in Unity. In my experience so far I find it quite annoying. I don’t know why…

Anyway, I hope someone has a simple solution for me?

Thanks!

I guess that is what you want:

1)Add boolean parameter “Start” (you can name it as you want I’ll just use that name in example) to your animator transitions. If true => set shine animation, if false => set idle animation.

2)Add this code to your diamond prefab:

public class Diamond : MonoBehaviour
{
    static bool diamondsCanShine = true;
    private Animator _anim;
    [SerializeField]
    private string startAnimation = "Start";
    internal bool isAnimated
    {
        get { return _anim.GetBool(startAnimation); }
        set { _anim.SetBool(startAnimation, value); }
    }
    private void Awake()
    {
        _anim = GetComponent<Animator>();
    }
    private void Start()
    {
        StartCoroutine(Example());
    }
    IEnumerator Example()
    {
        while (diamondsCanShine)//replace with something like "GameIsPlayedBoolean" or "LevelIsRunning" or "GameIsNotPaused" etc.
        {
            isAnimated = !isAnimated; //this will start and stop animation if animation never stops
            //though if your animation is not loooping and stops then you can always randomize boolean istead or check if (isAnimated) or (!isAnimated) and do what you expect accordingly
            yield return new WaitForSeconds(Random.Range(0f, 10f));//this will randomly wait next time the process changes, set min and max wait time
        }
    }
}