Search Unity

Animations run in background

Discussion in 'Scripting' started by nickavv, Jul 31, 2007.

  1. nickavv

    nickavv

    Joined:
    Aug 2, 2006
    Posts:
    1,801
    Hey all. ;) I have an animated 2d character who has two different animated textures right now (quicktime movies). To animate them I'm using this lil bit of code that I nabbed off of the documentation:

    Code (csharp):
    1. // Animate the texture frames
    2. var texture : Texture2D;
    3. var framesPerSecond = 12.0;
    4.  
    5. function Update () {
    6.     var frameIndex : int = Time.time * framesPerSecond;
    7.     // make the animation repeat by taking modulo
    8.     frameIndex = frameIndex % texture.frameCount;
    9.     // change texture frame
    10.     texture.frame = frameIndex;
    11. }
    12.  
    13. function Reset () {
    14.     if (renderer) {
    15.         texture = renderer.sharedMaterial.mainTexture;
    16.     }
    17. }
    But the problem is that when the current animation isn't the active material, it still plays invisibly, so next time I switch to that animation it starts not at its actual first frame (like it should), but from wherever it was in its hidden animation. Um, did you get all of that? So what should I do?
     
  2. Omar Rojo

    Omar Rojo

    Joined:
    Jan 4, 2007
    Posts:
    494
    Declare another variable and when the material is setted, start adding time to that variable starting from 0, its like having your own time

    Code (csharp):
    1. private var ownTime = 0.0;
    2. private var animating = false;
    3.  
    4. function Update ()
    5. {
    6.    if ( animating )
    7.    {
    8.       ownTime += Time.deltaTime;
    9.    }
    10.    else
    11.    {
    12.       ownTime = 0.0;
    13.    }
    14.  
    15.    var frameIndex = ownTime / framesPerSecond;
    16. }
    Here you control the animating variable so when the material is set, animating should be turned to true, and use ownTime to calculate the current frame.

    For performance reasons, you should put all your frame calculus code inside the if ( animating ) { }

    .ORG
     
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    The animations aren't really running; it's just that Time.time keeps going no matter what, and that's where the index value is coming from. (Annoying, isn't it...I propose that Unity 2.0 make it so that you can stop time. ;) ) So, use something else other than Time.time. Like instead of using Update, you could have the animation use a function that you call with InvokeRepeating or something.

    --Eric