- Home /
Object 'destroying' when it hits the wrong tagged objects...
Hi again :)
I have this code attached to a bullet script. I want the bullet to ONLY be destroyed when it hits objects with certain tags, and to ignore all others...BUT the 'bullet' is getting destroyed whenever it hits ANY collider. There is a rigidbody on the bullet.
function OnTriggerEnter(trigHit : Collider){
if(gameObject.FindWithTag("backdrop")){
Destroy(gameObject);
}
if(gameObject.FindWithTag("enemy")){
Destroy(gameObject);
}
Why is the bullet being destroyed when hitting an untagged/differently tagged collider?
Thank you for your continued help, Tom :)
Answer by ScroodgeM · Aug 16, 2012 at 11:55 AM
cause you just checking "is there somewhere an object with tag "backdrop" or "enemy"?"
use
if(gameObject.tag == "backdrop"){
instead
Totally 'facepalmed' myself after seeing this answer.
Thanks man, can't believe i didn't see that :)
Answer by Kryptos · Aug 16, 2012 at 12:00 PM
FindWithTag does not apply to the current object. It is a static method that looks for an object with the specified tag amongst all objects in the scene.
Therefore gameObject.FindWithTag()
and GameObject.FindWithTag()
is equivalent but different than if(gameObject.tag == "ATag")
.
In your example, you're always destroying the gameObject the bullet) that holds your script when a collision occurs. What you need to do is checking the tag of the collided object:
function OnTriggerEnter(trigHit : Collider)
{
var tag : String = trigHit.gameObject.tag;
if(tag == "backdrop")
{
Debug.Log("Hit a backdrop");
Destroy(gameObject);
}
else if(tag == "enemy")
{
Debug.Log("Hit an enemy");
Destroy(gameObject);
}
}
Thanks for replying, man.
Feel a bit daft for this one, i think i've been awake too long :)