your timer is set to ‘Time.time’ when this script is first loaded. This could have been any amount of time prior to ‘onTrigger’ flagging.
Try using ‘Invoke’:
Or BETTER use coroutines:
Example, rearranging your code as a coroutine:
var anim : Animation;
//instead of setting 'onTrigger' true, call this function... your bool approach is archaic!
public function SetTrigger()
{
StartCoroutine(PerformAnimRoutine());
}
private function PerformAnimRoutine()
{
//here we're going to use PlayQueued to get the animstate, with that we can determine some info about the anim
var state:AnimationState = anim.PlayQueued("anim_1", QueueMode.PlayNow, PlayMode.StopSameLayer); //0 from Play is StopSameLayer... use the enums, they're more explicit
yield WaitForSeconds(state.length);
state = anim.PlayQueued("anim_2", QueueMode.PlayNow, PlayMode.StopSameLayer);
yield WaitForSeconds(state.length);
gameObject.active = false;
}
In this instead of setting some bool ‘onTrigger’ to true when you want the sequence to play. We instead call the method ‘SetTrigger’. This will start the sequence.
In our sequence we use a coroutine to order the sequence.
We first play ‘anim_1’, and we do so with PlayQueued. The reason I do this is because if you use that function it returns the AnimationState for the anim we played. With that state information we can get the length of the animation from its property… no longer needing to hardcode the wait duration.
Next we yield a WaitForSeconds instruction saying to wait the duration of that animation.
Now we play “anim_2”, getting the state again, note I reuse the variable because no reason to make a new one… old anim is complete.
We again wait for the duration of the animation.
And NOW we disable the gameObject.
What’s nice about coroutines is that each line of code reads in the sequence of events that is actually going…
play
wait
play
wait
disable
NOTE… I don’t usually write unityscript/javascript, I’m a C# guy… so this was written right here in the browser. No guarantee it’ll work directly. I may have mispelled this that or the other.
Here it is in C#:
using UnityEngine;
using System.Collections;
public class ExampleScript : MonoBehaviour
{
public Animation anim;
public void SetTrigger()
{
this.StartCoroutine(this.PerformAnimRoutine());
}
private IEnumerator PerformAnimRoutine()
{
var state = anim.PlayQueued("anim_1", QueueMode.PlayNow, PlayMode.StopSameLayer);
yield return new WaitForSeconds(state.length);
state = anim.PlayQueued("anim_2", QueueMode.PlayNow, PlayMode.StopSameLayer);
yield return new WaitForSeconds(state.length);
this.gameObject.active = false;
}
}
There, much more familiar.