r/Unity3D • u/Marthgis • 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
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
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.