- Home /
two objects colliding
I have two of the same prefabs colliding and when they hit I want them both to delete. I can only ever get one to delete and not the other. how do I do that?
Answer by StephanK · Feb 15, 2011 at 02:23 PM
add a script to the prefab that does this:
function OnTriggerEnter(other : Collider) {
var destructable = other.GetComponent("Destructable");
if (destructable != null)
GameObject.Destroy(gameObject);
}
and is named Destructable.js. Now make sure your objects have a collider that is set to trigger and a rigidbody, otherwise there will be no collision/trigger at all.
Answer by e-bonneville · Feb 15, 2011 at 05:39 PM
In C#
void OnCollisionEnter(Collision collision) {
Destroy(collision.collider.gameObject);
Destroy(gameObject);
}
In Javascript
function OnCollisionEnter(collision : Collision) {
Destroy(collision.collider.gameObject);
Destroy(gameObject);
}
If it's 2 instances of the same prefab, Destroy(gameObject) should be enough when used in OnCollisionEnter, cause it would be called on both.
The very term instance indicates that it's separated from the original prefab in some way. If I call delete on one of the gameObjects, it will delete only that instance of it.
Yep, but both instances share the same prefab's methods, thus if the prefab contains a "Destroy self" method which is automatically called on collision detection, they should both call it and be destroyed.
Well, I must say, I've done a lot of work with prefab instances, and that is simply not the case. It does seem logical for both of them to be destroyed, but that's not what happens.
Hey Elliot, I don't want to be annoying, but I'm kind of new to Unity development (though not to scripting), thus I find this topic interesting in term of learning :) I tested what I was saying (2 instances of a prefab with a simple Destroy( this.gameobject) script), and it perfectly works. What kind of issues did you have?
Answer by Raymond 2 · Feb 09, 2011 at 08:44 PM
Try this script: var object1 : Transform ; var object2 : Transform ; function Update () {
function OnTriggerEnter (){
Destroy(object1.gameObject); Destroy(object2.gameObject);
}
}
i dont think that would work because they are both the same prefab
But in the scene there will be 2, so then it should work
eventually though i'm going to want more of the prefabs. like a few hundred at least
that didnt seem to work. for some reason they won't even spawn anymore when i make them triggers. and I keep getting the expected ( found OnTriggerEnter error when I put it in the update function.
Your answer
Follow this Question
Related Questions
Collide detection with tag [JS] 0 Answers
Analysing player metrics help 0 Answers
Getting info about hit Object (Javascript). 1 Answer
2D Collision 1 Answer
NullReference on Collision 1 Answer