- Home /
Question by
OxenEknat · Jun 09, 2014 at 09:54 PM ·
oncollisionenterinvoke
[SOLVED]Destroy gameObject, not OnCollisionEnter but after a while
I need to make my GameObject destroy after tot seconds from the collision. I tried both with OnCollisionEnter() and a Timer and with Invoke("Destroy", Timer) but it simply collides without destroying.
public void Destroy()
{
Destroy(this.gameObject);
}
public void OnCollisionEnter(Collision collision)
{
ContactPoint contact = collision.contacts[0];
Quaternion rot = Quaternion.FromToRotation(Vector3.up, contact.normal);
Vector3 pos = contact.point;
GameObject istanza = (GameObject)Instantiate(particles, pos, rot); //until this point the OnCollisionEnter is taken from docs.unity3d.com, and it works
if (collision.gameObject.tag.Equals("Item"))
{
if (PlayerPrefs.GetString("ItemKept", null) == bestItem)
{
float Timer = //expression to define how much should I wait
Invoke("Destroy", Timer);
} else if (PlayerPrefs.GetString("ItemKept", null) == null)
{
float Timer = //expression to define how much should I wait
Invoke("Destroy", Timer);
}
else if (PlayerPrefs.GetString("ItemKept", null) != bestItem)
{
float Timer = //expression to define how much should I wait
Invoke("Destroy", Timer);
}
}
}
P.S. Please forgive Grammatical error, I'm a non-Anglophone student. EDIT: Works perfectly now, I forgot to put the hitting item's tag and I used a float "life"; I make it smaller every hit and, to save the changes to life, I use PlayerPrefs.SetFloat("TempLife", life) and life=PlayerPrefs.GetFloat("TempLife", life)
Comment
Answer by Mulldor · Jun 09, 2014 at 10:13 PM
You can put in a delay by yourself in the Destroy method. I.e, delay destruction with 5 sec: Destroy(gameObject, 5f);
Your answer
![](https://koobas.hobune.stream/wayback/20220613151206im_/https://answers.unity.com/themes/thub/images/avi.jpg)