- Home /
Collision between 2 prefabs.
I'm trying to detect collision between a bullet and a target both of them are prefabs that are moving objects. This is the code i've attached to the bullet for detecting collision using UnityEngine; using System.Collections;
public class collision : MonoBehaviour {
void OnCollisionEnter(Collision collide){
if(collide.gameObject.name == "target"){
print("hit");
Destroy(collide.gameObject);
Destroy(this.gameObject);
}
}
}
Both the target and bullet are rigidbodies and collide and everything but the code within if statement is not getting executed..
Answer by syclamoth · Jan 16, 2012 at 07:23 AM
The problem is that when an object gets instantiated, it gets the word "(clone)" appended to its name! If your prefab is called "target", then the names of the actual objects will be "target(clone)".
While a quick fix would be to change the if statement to include that, a better way would be to have it detect tags, instead of names. You can never be sure what the name of a given object will be if if has been cloned a few times, since the 'clone' word gets appended every time.
Instead, give both objects the tag "target", so that when they collide you can use
if(collide.gameObject.tag == "target")
{
// Destroy things
}
This way, any object with the correct tag will trigger this code.
Your answer
Follow this Question
Related Questions
Collision between 2 prefabs. 0 Answers
How to only delete one of two collided objects? 1 Answer
Destroying all objects with a certain tag that ray cast if colliding with 0 Answers
How to destroy bullet on collision! 2 Answers
The object of type 'Rigidbody' has been destroyed but you are still trying to access it. 2 Answers