- Home /
Triggering over time?
How to use a trigger in combination with time?
I want a GameObject to be destroyed 2 seconds after being in interaction with the trigger, and I thought something like this should work:
function OnTriggerEnter(other : Collider)
{
if(other.gameObject.Tag == "Player && Time.deltaTime > 2)
{
Destroy(gameObject);
Debug.Log(Destroyed after 2 Seconds of interaction");
}
}
But it is not working correctly, only if I set the time variable really low. <--- This is solved due to the fact that I forgot about the CoRoutines, Thanks dannyskim
Edit
The answer from dannyskim was the one that solved my problem, creating a Timer, and using OnTriggerStay instead of OnTriggerEnter....
This is my result:
//
private var startTime;
//
function OnTriggerStay(other : collider)
{
if(other.gameObject.Tag == "Player")
{
Debug.Log("Player OnTriggerStay");
startTime = Time.time;
//
if(startTime >= 4.0)
{
Debug.Log("Player destroyed GO");
ResetTimer();
Destroy(gameObject);
}
}
}
//
function OnTriggerExit(other : Collider)
{
if(other.gameObject.Tag == "Player")
{
Debug.Log("Player OnTriggerExit");
ResetTimer();
}
}
//
function ResetTimer()
{
startTimer= 0.0;
}
Answer by dannyskim · Jan 31, 2012 at 05:37 PM
Best to probably just stick your Destory() inside of a CoRoutine, you can't just halt execution of OnTrigger as it behaves like any other runtime method .
StartCoroutine( destroyGO(2, gameObject) );
function destroyGO( wait : float, go : GameObject )
{
yield WaitForSeconds(wait);
Destroy(go);
}
This destroys every GameObject 2 Seconds after it has been triggered by the Player. But I want the GameObjects only to be destroyed if it is triggered at least 2 seconds by the Player.
Then you should be using OnTriggerStay, not OnTriggerEnter.
http://unity3d.com/support/documentation/ScriptReference/Collider.OnTriggerStay.html
And deltaTime is a calculated constant, meaning that it's always going to return an extremely small value. If you read the documentation, you'll see that it states deltaTime being the time it took to calculate the last frame. $$anonymous$$ost likely it will never be above 2 then. You have to create your own timer.