This is probably a simple script, but it’s behaving different to what I’d imagine. The goal here was to have an object simply wait out it’s time, then destroy itself, but just before it destroys it’s self, I was hoping it would flash a bit.
What’s happening is close to what I thought would happen, except the flashes are very, VERY quick. (like it’s not waiting for the seconds I’ve told it to wait before it re enables or disables the mesh renderer.)
What am I missing here?
#pragma strict
var waitTime : float = 10;
var flashLength : int = 5;
function Update ()
{
FlashObject ();
DestroyObject ();
}
function DestroyObject ()
{
yield WaitForSeconds (waitTime);
Destroy ( gameObject );
}
function FlashObject ()
{
yield WaitForSeconds ( 4 );
var i = flashLength;
for (; i >= 0; i--)
{
renderer.enabled = true;
yield WaitForSeconds ( 5 );
renderer.enabled = false;
yield WaitForSeconds ( 5 );
}
}
The problem is that you are calling FlashObject() and DestoryObject() at every Update() call. So in the 10 seconds you wait to destroy the game object, you stack up 300 - 1000 coroutines, all executing at the same time, all offset in time by the a single deltaTime. To better see what is going on, change your update code to:
function Update ()
{
if (Input.GetKeyDown(KeyCode.Space)) {
FlashObject ();
DestroyObject ();
}
}
Then you can press the space bar. Note you could assure your timing was accurate by eliminating the DestoryObject() function and inserting the Destory(gameObject) as the last line in your FlashObject() function.