Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Resolved OnCollisionEnter Never Called Despite Colliding

Discussion in 'Scripting' started by Mortichar, May 19, 2022.

  1. Mortichar

    Mortichar

    Joined:
    Mar 30, 2017
    Posts:
    19
    I'm currently having an issue where my bullet object (with a rigidbody and sphere collider) is colliding with my shield (sphere collider) and bouncing off, yet a script I have attached to my shield that overrides OnCollisionEnter is never getting called.

    My bullet prefab, with a sphere collider and non-kinematic rigidbody:

    upload_2022-5-18_19-16-3.png

    upload_2022-5-18_19-12-29.png

    My Shield, which is part of a prefab:

    upload_2022-5-18_19-13-49.png

    And the player, which is the parent of the Shield and has a non-kinematic rigidbody (which is why the bullets push it around):

    upload_2022-5-18_19-15-22.png

    The bullet are bouncing off of the shield, as expected (zipped .mp4): bouncing_bullets.zip


    Function signature:
    Code (CSharp):
    1.     void OnCollisionEnter(Collision collision)
    2.     {
    3.         if (collision.gameObject.tag == "Projectile")
    Both of my colliding objects have colliders, neither is a trigger, and they are both non-kinematic. What am I missing?
     

    Attached Files:

  2. Mortichar

    Mortichar

    Joined:
    Mar 30, 2017
    Posts:
    19
    I managed to solve this. The problem seems to be that the script was on the object with the collider, not the parent object with the rigidbody.
     
    Kurt-Dekker likes this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    25,914
    Excellent! Feels good, doesn't it?

    Also, just in case, keep this in mind for possibly missing physics calls:

    With Physics (or Physics2D), never manipulate the Transform directly. If you manipulate the Transform directly, you are bypassing the physics system and you can reasonably expect glitching and missed collisions and other physics mayhem.

    Always use the .MovePosition() and .MoveRotation() methods on the Rigidbody (or Rigidbody2D) instance in order to move or rotate things. Doing this keeps the physics system informed about what is going on.

    https://forum.unity.com/threads/col...-unity-physic-rigidbody.1216875/#post-7763061

    https://forum.unity.com/threads/oncollisionenter2d-not-being-called.1266563/#post-8044121

    With a wheel collider, use the motor or brake torque to effect motion.
     
  4. Mortichar

    Mortichar

    Joined:
    Mar 30, 2017
    Posts:
    19
    The only way I've been moving my objects so far is with AddForce and AddTorque.
     
    Kurt-Dekker likes this.
unityunity