- Home /
Checking for a name on collision (solved!)
I've been through the script reference for Collision and some other questions on unityAnswers, and they all lead me to believe that my code should work, but evidently I've done something wrong. Take a look.
void OnCollisionEnter(Collision collide)
{
if(collide.gameObject.name == "Hitbox")
{
Destroy(gameObject);
}
}
I know that the collision is being recognized, because if I remove the if statement, the object is destroyed just fine, and if I leave it in, the two rigidbodies still interact physically. They're both RigidBody/Colliders, so that shouldn't be a problem anyway. Additionally, I've tried a few permutations of "collide.collider.(etc)" to no avail. Hitbox is a prefab I've constructed.
I'm kind of embarrassed that I'm having so much trouble with this, but clearly I'm missing something here. Thanks a lot for any help you can provide.
Edit:
I was able to create a workaround by assigning a tag to the Hitbox prefab and checking for that instead like so:
if(collide.gameObject.tag == "Hitbox")
I'm not sure if this will cause problems for me later, but it seems to work for now.
Edit 2:
It turns out that object's name was being processed as "Hitbox(Clone)". I followed the advice of an answer here and had the name written to the debug log.
Try :
Debug.Log( "collide (name) : " + collide.collider.gameObject.name );
Debug.Log( "collide (tag) : " + collide.collider.gameObject.tag );
if(collide.collider.gameObject.name == "Hitbox")
Thanks, Alucard, that really helped. (Coincidentally, I'm using the Alucard sprite from SotN as a placeholder in this project~)
It turns out the object's name is being processed as "Hitbox(Clone)".
Ah, yes, instantiated object append (clone) to the name. Do some rena$$anonymous$$g when instantiating :
var clone : GameObject = Instantiate ( ....
clone.name = "Hitbox";
Alucard J, yes I am a creature of the night >:D
In that case you'd be able to use .Contains("Hitbox") or .StartsWith("Hitbox") depending on how accurate you need to be. (Starts with runs very slightly faster too)
Answer by AlucardJay · Apr 04, 2013 at 05:33 PM
OnCollisionEnter is a collision event, you want to access the collider component involved in that event. From my comments :
Debug.Log( "collide (name) : " + collide.collider.gameObject.name );
Debug.Log( "collide (tag) : " + collide.collider.gameObject.tag );
if(collide.collider.gameObject.name == "Hitbox")
(on further information) : Ah, yes, instantiated object append (clone) to the name. Do some renaming when instantiating :
var clone : GameObject = Instantiate ( ....
clone.name = "Hitbox";
Your answer
Follow this Question
Related Questions
Collision between two moving clones 0 Answers
Hit Detection Issues with multiple colliders on 1 mesh? 1 Answer
Can prefabs interact with scroll rect? 0 Answers
Destroy a specific prefab (GameObject) Unity2D 1 Answer
Tagged collision problem 1 Answer