Activating object for certain limit of time

Hi, i would like my object to be visible only for 60 seconds and then it disappear from the screen. however when i deactivate the object after 60 seconds, the objects does not appear at all in the screen.I used “debug.log” to test whether the loop i used for the time limit is correct or not.it worked just fine but the statement “it’s in” only came out after a while like 60 seconds. i tried to use coroutine but still couldn’t work. hope someone can help to solve my problem. Thank you.

void OnTriggerEnter( Collider col)
{ float timeLeft = 0.0f;

	if (col.gameObject.tag == "Player") 
	{	 timeLeft = 60.0f;
		while(timeLeft > 0.0f)
		{   timeLeft -= Time.deltaTime;
			Fig [0].SetActive (true);	
			Fig [1].SetActive (true);	
			Debug.Log("it's in");
			
		}
	
		StartCoroutine("WaitHere");
		
	 }	// end if			
}//end function on trigger enter

IEnumerator WaitHere()
{
	Debug.Log("it's out");
	
		Fig [0].SetActive (false);	
	        Fig [1].SetActive (false);
	
	
	yield return 0;
	
}// end waithere

hmm, what is the problem exactly? that the debulog wont print after 60 seconds, or the object doesnt activate / deactivate? your question seems abit unclear to me sorry

Have you looked into WaitForSeconds http://answers.unity3d.com/questions/350721/c-yield-waitforseconds.html

wait, the script sets the object .SetActive to false... but then you want it to reactivate again after 60 seconds? Won't deactivating the object also deactivate the script running on it, leaving nothing to 'wake it up again'?

ohh sorry. i'll try suggestions given by yash first and see how's it.anyway thank you for yield wait for second link

Thank you yash, i've got it based on your suggestion.

1 Answer

1

Problem is while loop inside trigger function. What happens here is loop executed 60 times not in different frames but 60 times in just a single frame.
When you start a coroutine it won’t stop main flow it is executed alongside any other function.

Solution is remove loop from trigger and add it in coroutine. add “yield return null;” as the last line of loop. Now print something before loop and after the loop.

Play around with coroutines and different yield instructions. Coroutines are very useful . All the best. :wink:

thank you. i'll try