- Home /
Why is my OnCollisionEnter function working for enemies and not my player?
I am trying to use tags to limit the OnCollisionEnter function to only trigger when a certain type of shot collides. I have nearly identical functions on my enemies as I do on the player, yet the one on the player is not working.
On the enemy I put:
function OnCollisionEnter(collision : Collision) {
//Player shot hits enemy, enemy explodes, score points
if(collision.gameObject.tag == "PlayerShot"){
gameController.AddScore (scoreValue);
Instantiate(explosion, transform.position, transform.rotation);
Destroy (gameObject);
}
//Player collides with enemy, both die, game over
if (collision.gameObject.tag == "Player"){
Destroy (collision.gameObject);
Instantiate(explosion, transform.position, transform.rotation);
gameController.GameOver();
Destroy (gameObject);
}
}
Which is working as intended. Enemies do not blow themselves up with their own shots and die when shot by the player.
On the player I have:
function OnCollisionEnter(collision : Collision) {
//Enemy shot hits player, player explodes, game over
if(collision.gameObject.tag == "EnemyShot"){
Instantiate(explosion, transform.position, transform.rotation);
gameController.GameOver();
Destroy (gameObject);
}
}
Everything is correctly tagged and I'm not getting any errors, but the enemy shots just pass right through. What am I missing?
you likely need to get in to unity's very awesome LAYERs system. physics layers. check out the doco
If you have a character controller on your player, they don't always get OnCollisionEnter called on themselves. You could try: http://docs.unity3d.com/Documentation/ScriptReference/CharacterController.OnControllerColliderHit.html ins$$anonymous$$d.
Neither of those suggestions work. They are already on the same layer, so until I solve the detection issue putting them on a different layer does nothing.
Also I wrote my own code to control the player. It does not have a character controller on it.
Edit: Put a rigidbody on the enemy shot and it worked.
Does your player have a rigidbody and a Collider attached?, As far as I know, OnTriggerEnter requires a rigidbody if you're not using CharacterControllers. Let me know if that worked for you
Answer by Xroft666 · Oct 23, 2012 at 09:16 PM
Note that collision events are only sent if one of the colliders also has a non-kinematic rigidbody attached.
http://docs.unity3d.com/Documentation/ScriptReference/Collider.OnCollisionEnter.html
That fixed it. Put a rigidbody on my player and it worked. Thanks!
Your answer
Follow this Question
Related Questions
OnCollisionEneter() does nothing C sharp 0 Answers
Boo & Collision 1 Answer
Objects in my scene are not responding to OnCollisionEnter 0 Answers
Using collision with Vector3.MoveTowards 3 Answers