Search Unity

Problem with OnCollision

Discussion in 'Scripting' started by Trild123787898, Feb 16, 2020.

  1. Trild123787898

    Trild123787898

    Joined:
    Dec 9, 2018
    Posts:
    206
    why does not want to work ??

    Code (CSharp):
    1.  
    2.     private Rigidbody two_rb;
    3.     GameObject obj;
    4.  
    5.  
    6.  
    7.     void OnCollisionExit(Collision exit)
    8.     {
    9.      
    10.  
    11.             two_rb = obj.AddComponent<Rigidbody>();
    12.  
    13.  
    14.     }
    15.  
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Not sure of your full codepath and object setup, but I see you are adding a Rigidbody... if you don't already HAVE a Rigidbody, none of these collider/trigger functions will be called. See the docs:

    https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionExit.html

    I quote:

    "Collision events are only sent if one of the colliders also has a non-kinematic rigidbody attached."
     
  3. Trild123787898

    Trild123787898

    Joined:
    Dec 9, 2018
    Posts:
    206
    I already understood this. Can I somehow solve this? when the object touches terrain the rigidbody is deleted and when it no longer touches then I need to add the rigidbody back, with OnCollisionEnter everything is fine with me, but it doesn’t work with OnCollisionExit
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Can you just set the
    Rigidbody
    to be
    isKinematic
    (on initial collsion) instead of deleting it? That's usually the way you take things out of the Physics simulation if you intend to put them back in later...

    Alternately maybe you can have a proxy invisible collider object whose Rigidbody you DON'T delete, and that has connections over to your current object, but that can get a little bit tricky.
     
  5. Trild123787898

    Trild123787898

    Joined:
    Dec 9, 2018
    Posts:
    206
    no iskinematic for me no way