- Home /
Incorrect Collision Detection
I am having a major problem with my collision detection. If my main character attacks more than 10 times, Unity begins to detect a collision between the main character's sword and all of the enemies even when there is none. Here is the code I am using:
function OnTriggerEnter (other : Collider)
{
if(other.gameObject.name == "Main_Sword")
{
Debug.Log("Hitting me");
}
}
With this code, the message "Hitting Me" will continously print out after the Main Character attacks more than 10 times, regardless of where the Main Character is. I am positive that there is no collision, yet Unity thinks that there is one. Is there any way I can fix this or anything I can do?
Answer by spinaljack · May 01, 2010 at 09:16 AM
Is the collider in a child object? Because your script only checks the name of the game object with the collider on it. (not necessarily the root game object)
Simple way to fix this is to change the name of the child object which has the collider in it.
Another theory might be the way you're handling enemies being spawned or killed, maybe they're leaving colliders behind or in unexpected places.
Screenshot might be nice.
Answer by Peter G · May 01, 2010 at 11:35 AM
To me, it looks like you are creating a trigger for the wrong object. Normally you would put the trigger on the sword because the sword is the weapon and then you have to put one script on the sword instead of ten for each of the enemies.
function OnTriggerEnter (other : Collider)
{
if(other.gameObject.tag == "Enemy")
{
Debug.Log("Hit Enemy");
}
}
I don't know if that would cause your problem, but if can't find an answer it is probably worth trying.
Answer by Garrett Chase · May 03, 2010 at 09:16 PM
Thanks for your ideas spinaljack and Peter G. To spinaljack, the colliders are on the root object, and I checked the way I was killing and spawning enemies. I didn't leave colliders out or anything like that, and even looking in the Scene window, I saw no collisions when it said there was. To Peter G., I also tried your idea and was still detecting collisions when there was none. If anyone has any other ideas I would be very grateful. This is a very frustrating problem that is seriosly affecting my application.
Answer by Garrett Chase · May 06, 2010 at 09:18 PM
I solved the problem. Actually, I avoided it. Using a capsule collider on the sword's blade creates this error every time, however, using a box collider eliminates the error. I don't know why, but it works so I'm happy. Thanks for all of the help.
Your answer
Follow this Question
Related Questions
Help with collision detection with specific colliders 1 Answer
Collision problem in C# 4 Answers
Problem with the collider(I think) 0 Answers
Using shadows as Triggers? 1 Answer
How to restart scene with trigger? 1 Answer