r/Unity3D • • 1d ago

Question collider problem with an empty

 In my Unity project, I want an empty GameObject—containing only a collider and named "attack"—to destroy an enemy (the red rectangle). I’m using a tag called "sword," but it doesn't work; however, when I do the exact same thing using the player object, it works fine. How can I fix this? Here is the line of code I’m using on the enemy script:
private void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("Sword"))
{
Destroy(gameObject);
}
}

4 Upvotes

5 comments sorted by

8

u/Goldac77 1d ago

Your empty collider has "IsTrigger" ticked. So you need to use OnTriggerEnter(), not OnCollisionEnter()

1

u/BFS-9000 1d ago

Try it with Rigidbody attached to one of objects, like you have it on your Player object.

1

u/SurocIsMe 1d ago
  1. Do you have a collider to the red gameobject?
  2. as u/Goldac77 said, use OnCollisionEnter
  3. you say you use a tag called "sword" but then in your code you use "Sword", make sure you use the correct one and you have add the tag to your red gameobject.

1

u/BigMustach69 1d ago

You should use OnTriggerEnter() instead since you set the collider to Trigger in the inspector

1

u/johnv_dev 1d ago

two things i'd check. your tag is "sword" in the post but the code checks "Sword", and CompareTag cares about capital letters, so those have to match exactly. also, other.gameObject gives you the object that has the rigidbody, not the one with the collider. so if attack is a child of the player, it's really seeing the player. try other.collider.CompareTag("Sword") instead. and if attack isn't on anything with a rigidbody, give it a kinematic Rigidbody, or no collision fires at all.