GameObject.FindWithTag doesn't work!

Here’s my script:

#pragma strict

var CrystalHealth : float = 100;
var Effect : GameObject;
var GemSpawner : GameObject;

function Update() {
var Bomb = GameObject.FindWithTag("Bomb");

if (CrystalHealth<=0) {
Instantiate(GemSpawner, this.transform.position, Quaternion.identity);
Destroy(this.gameObject);
}
}

function OnCollisionEnter(Bomb : Collision) {
CrystalHealth=CrystalHealth-100;
Instantiate(Effect, this.transform.position, Quaternion.identity);
}

When the object who has the script attached to it collides with…anything, also with object that hasn’t the tag “Bomb”, the CrystalHealth goes to 0 and the object destroys himself. How can i fix this? I’ve also tried using GameObject.FindGameObjectWithTag and GameObject.Find. Nothing. Please help me!

Your problem does not appear to be with GameObject.FindWithTag(). The parameter passed into OnCollisionEnter is not always going to be the bomb. Every object that collides with the object this script is attached to will be passed into the OnCollsionEnter function. Your tag check should be placed in the OnCollisionEnter function and if it is a “Bomb” you proceed, otherwise return.

function OnCollisionEnter(otherObject : Collision)
{
if(otherObject.gameObject.tag == "Bomb")
{
CrystalHealth=CrystalHealth-100;
Instantiate(Effect, this.transform.position, Quaternion.identity);
}
}

The var Bomb variable you created is completely separate from the variable passed as the parameter in the OnCollsionEnterFunction.