- Home /
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!
var Bomb = GameObject.FindWithTag("Bomb");
Do that in your Start() or just set it in the editor (attribut should be public then).
Instantiate(Effect, this.transform.position, Quaternion.identity);
Same thing, don't instatiate here. Place your effect inside the GameObject wanted, and active/desactive it in your OnCollisionEnter() function (by the way you should use OnTriggerEnter here i guess).
Instantiate(GemSpawner, this.transform.position, Quaternion.identity);
Same.
Do that first.
Answer by Ed unity · Mar 26, 2014 at 03:27 PM
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.
Your answer
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Destroying Multiple Objects with Tags 1 Answer
destroying children also destroys parent itself 4 Answers
When all objects with a certain tag has been destroyed, load the next level! 3 Answers
create a destroyer for 2d infinite runner game objects. 2 Answers