basically i have a scene with 3 ghosts and i want to be able to shoot them and have them disappear when hit, simple you would think. this script is attached to each of the ghosts. it all compiles fine but does nothing when i run it. Not even the print line. im 100% sure its something to do with this if(col.gameObject.name == “ghost1”. no idea what though.
im reasonably new to unity btw.
var ghost2 : GameObject;
var ghost1 : GameObject;
var ghost3 : GameObject;
function OnCollisionEnter (col: Collision) {
if(col.gameObject.name == "ghost1"){
ghost1 = GameObject.Find("ghost1");
Destroy(ghost1);
print("You hit ghost1");
//audio.Play();
}
else
if(col.gameObject.name == "ghost2"){
ghost1 = GameObject.Find("ghost2");
Destroy(ghost2);
print("You hit ghost2");
//audio.Play();
}
else
if(col.gameObject.name == "ghost3"){
ghost3 = GameObject.Find("ghost3");
Destroy(ghost3);
print("You hit ghost3");
//audio.Play();
}
}
The logic is a little off as @Divinyx pointed out. Here is something that should get the results you are looking for.
function OnCollisionEnter (col: Collision)
{
//Tag is a much better value to use since name can change.
if(col.gameObject.tag == "bullet")//We care if a bullet hits this object not if a ghost hits this ghost.
{
//This ghost was hit by a bullet so lets kill it.
Destroy(this.gameObject);
Destroy(col.gameObject); //Also kill the bullet since it hit someone.
audio.Play(); //Play your sound.
}
}
This would be placed on each ghost to make it work. Also make sure you tag your bullets with your new tag. Click tag-> Add Tag → Make a new one called Bullet → Tag your bullets.