- Home /
How do i destroy only 1 object when 2 instances of the same object collide ?
Sorry im at work and don't have access to my code but basically. If i set it to destroy the "other" since nothing is destroyed until the end of the update both objects get flagged for destruction. I don't care which one survives for right now just trying to understand the idea of how to do this. In the future i might create a new instance where the 2 hit but again then both would trigger the creation of a new instance and the 2 new instances would collide ect ect.
Answer by Kiwasi · Jan 13, 2015 at 09:16 PM
Simply set a flag for destruction. This will destroy only the first object to run this code.
public bool isDestroyed;
void OnCollisionEnter(Collision coll){
if(!coll.gameObject.GetComponent<MyScript>().isDestroyed) {
isDestroyed = true;
Destroy(gameObject);
}
}
I was honestly thinking about this this morning but could not test it and thought maybe there was some kind of built in solution i was missing and was not sure if it would work because of the order of events. Ill test it when i get off work. Thank you
Answer by tanoshimi · Jan 13, 2015 at 07:00 PM
If you don't mind which one survives then you could pick an arbitrary property on which to compare the two colliding objects - say, destroy the one whose transform has the highest y value, as follows (untested):
void OnCollisionEnter(Collision coll){
if(coll.gameObject.transform.position.y > transform.position.y) {
Destroy(gameObject);
}
}
that would work, but is there not a more elegant solution? Thanks