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;
}
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);
}