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.

i.e

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

    void Update()
    {
        if (_animating)
            Animate();
    }

    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.

Thanks

The same problem for me using examples on:

or:
http://unity3d.com/support/documentation/ScriptReference/Material-mainTexture.html
or:

or:
http://unity3d.qatohost.com/questions/13156/animated-gif-as-a-texture-on-iphone.html?sort=oldest

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:

http://forum.unity3d.com/threads/33263-Anyway-to-get-animated-textures-in-Unity-Indie?p=587563&viewfull=1#post587563

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!