Skip to main content
2 of 3
Your problem has nothing to do with the switch statement
DMGregory
  • 140.8k
  • 23
  • 257
  • 401

How to change animation coroutine when a variable changes, not every frame?

I want to be able to change the enum animation mode at runtime.

This way will start the coroutine every frame in Update, but I want to start the coroutine only if the value of the enum variable has changed.

public enum AnimationType { None, SingleColorMorph, MultiColorMorph, Shuffle, Shift };
    public AnimationType myAnimationType;
    LineRenderer myLineRenderer;
    public float morphTime;

    void Start()
    {
        myLineRenderer = this.GetComponent<LineRenderer>();
        switch (myAnimationType)
        {
            case AnimationType.SingleColorMorph:
                StartCoroutine(RandomSingleColorMorphing(myLineRenderer, morphTime));
                break;
            case AnimationType.MultiColorMorph:
                StartCoroutine(RandomMultiColorMorphing(myLineRenderer, morphTime));
                break;
            case AnimationType.Shuffle:
                StartCoroutine(ShuffleGradient(myLineRenderer, .5f));
                break;
            case AnimationType.Shift:
                StartCoroutine(AnimateLoop(myLineRenderer));
                break;
        }
    }

    private void Update()
    {
        switch (myAnimationType)
        {
            case AnimationType.SingleColorMorph:
                StartCoroutine(RandomSingleColorMorphing(myLineRenderer, morphTime));
                break;
            case AnimationType.MultiColorMorph:
                StartCoroutine(RandomMultiColorMorphing(myLineRenderer, morphTime));
                break;
            case AnimationType.Shuffle:
                StartCoroutine(ShuffleGradient(myLineRenderer, .5f));
                break;
            case AnimationType.Shift:
                StartCoroutine(AnimateLoop(myLineRenderer));
                break;
        }
    }
Daniel Lip
  • 1.8k
  • 4
  • 40
  • 81