Sprite animation problem

I have a plane with a texture on it. The texture is looping through a bunch of materials assigned to it to give the idea of an animated sprite.


public void StartAnimation()
        active = true;
        renderer.enabled = true;
        _animating = true;
        _animationIndex = 0;
        _firstShown = false;

    void Update()
        if (_animating)

    private void Animate()
        // Loop through the materials to animate
        _animationIndex = Convert.ToInt32(Time.time / changeInterval);
        _animationIndex = _animationIndex % materials.Length;
        renderer.sharedMaterial = materials[_animationIndex];

        // If the final material is reached, stop animating and hide the gameobject
        if (_animationIndex == materials.Length - 1)
            _animating = false;
            renderer.enabled = false;
            active = false;
            _animationIndex = 0;

The problem is I need to show this animating sprite as it goes through its animation loop, then hide it. Then if I show it again, it must start at the beginning of its loop, then disappear again. Whats happening is as I show it, it seems to randomly be starting at certain frames of the animation loop, and never starting from the beginning. I’ve enabled/disabled it yet it still seems random.


The same problem for me using examples on:



This is because of Time.time value when starting animation. See the lines:

animationIndex = Convert.ToInt32(Time.time / changeInterval);
_animationIndex = _animationIndex % materials.Length;

For example, supposing you have 10 materials:

  • you start animation when Time.time = 38.29
  • integer is 38
  • 38 % 10 = 8
  • List item

So that animation will start with index 8.

I’am not sure about the best solution (maybe taking care to start any animation when Time.time % materials.Length == 0)

But I found a possible better solution here:


I tried this a while back, it is pretty hard to make work, I suggest modifying this script I have a 2D character that moves and use like 5 different game objects that I toggle if active all attached to one game object. In other words I have 5 planes that I turn off an on dependent on key input. Hopes this helps!