Coroutines and Active state

If you are going to de-activate an object in a script attached to that object (gameObject.active = false) it seems you have to call a coroutine AFTER you have set active to false. If you do it before then the coroutine is not called. Thus in the code:

//-------------------------------------------------- 
 function OnMouseDown () { 
//-------------------------------------------------- 
       
   gameObject.active = false;  
   StartCoroutine("testroutine");  // Is called
 
}

does execute the “testroutine”, but the code:

//-------------------------------------------------- 
 function OnMouseDown () { 
//-------------------------------------------------- 
   
   StartCoroutine("testroutine");     // Isn't called now
   gameObject.active = false;  
   
 
}

does not appear to execute the coroutine (I should add the coroutine has a yield statement in it). Is the above behaviour correct? The strange this is that in the latter case I get a console error messgage (below).

thanks,
Richard.

2043--72--$activeerror_856.jpg

Since you make the object inactive, neither of them should allow you to continue running the coroutine. Inactive objects are really inactive. No script functions or other methods get called on them, neither should coroutines.

That it allows you to run the coroutine after you have deactivated the game object is a bug.

Ok - thanks. So I guess and automated activation-deactivation will have to be done via a script attached to another object eg the parent?

What I am trying to do is make an object disappear when it is clicked on and then re-appear at a short random time interval later. At the moment all I can think of is for the clicked on object to set a flag in, say, it’s parents script. The parent checks the flag every frame and if it changes the parent deactivates the child and spawns a coroutine that later re-avtivates the child.

Is there another way of doing this?

many thanks,
Richard.

You could use layers for this.

  1. Create an invisible geometry layer in the Edit->Project Settings->Tags
  2. Setup the camera to not render objects with this tag using the culling Mask property.
  3. change the layer to the invisible geometry layer. A few seconds later, set it back to the default layer.

Excellent - the kind of clean solution I like! I’ll give it a go and report back.

thanks,
Richard.