How to destroy GameObject if it overlaps another GameObject
I have a prefab that is being spawned in in a random location. This prefab has only a box collider attached to it and a script. The collider is not a trigger.
How can I destroy the prefab if it intersects with another prefab?
The problem that I am having is that when the prefab spawns in, it DOES NOT trigger the collision and thus I cannot destroy the gameobject. onCollisionEnter DOES NOT WORK.
BONUS: Make sure only one prefab destroys itself, not both.
If you need any more info, just ask! Please guys, I'm desperate and I don't think I can make a workaround.
I will give you 30 points if you answer the question!
Another shameful bump. There's only so many ways I can google something...
Answer by MacDx · Sep 05, 2017 at 02:14 AM
Since you said "overlap" I'll assume you are working with triggers.
Create a tag and then add this method to the prefab's attached script.
void OnTriggerEnter(Collider other)
{
if(other.CompareTag("yourCreatedTag")
{
Destroy(this.gameObject);
}
}
This will destroy the prefab when it overlaps with an object that has that specific tag assigned. You could also check if the "other" object contains a specific component instead of a tag.
If you want them to be of the same type and have only one of them be destroyed then you need to assign them some kind of priority. You could do a check to see which one was going faster, or give them priority value so each of them would do a comparison of this value and then act accordingly.
Ah, I am not using triggers as the player in my game needs to collide with them.
Also, I have already tried this method, but it doesn't work. When the prefab spawns in, it doesn't trigger the collider.
But, thanks for the effort anyway.
If you are not using triggers then it's obvious that this method won't work lol, that's why it's called OnTriggerEnter. Try replacing OnTriggerEnter with OnCollisionEnter
like this:
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("yourCreatedTag"))
Destroy(this.gameObject);
}
P.S. make sure that you properly tagged the objects
When the prefab spawns in, it doesn't trigger a collision. This is the most frustrating part.
Answer by Saripsis · Oct 02, 2017 at 10:16 AM
Have redundant collision detection, one on each object.
Spawned Object:
void OnCollisionEnter(Collision col)
{
if (col.gameObject.tag == "WhateverTheTagIs")
Destroy(this.gameObject);
}
Existing Object:
void OnCollisionEnter(Collision col)
{
if (col.gameObject.tag == "WhateverTheTagIs")
Destroy(col.gameObject);
}
As I said above, the objects do not collide when they are spawned inside each other, but thanks for your efforts!