Search Unity

Nullpointer Exception by OnCollisionEnter

Discussion in 'Scripting' started by Manato, Mar 23, 2018.

  1. Manato

    Manato

    Joined:
    Jun 11, 2015
    Posts:
    28
    Hi, I got a Nullpointer in OnCollisionEnter while colliding.
    Here a sample:

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class Monotest : MonoBehaviour
    4. {
    5.     Rigidbody body;
    6.  
    7.     void Start()
    8.     {
    9.         body = GetComponent<Rigidbody>();
    10.     }
    11.  
    12.     void OnCollisionEnter(Collision other)
    13.     {
    14.         if (body == null)
    15.             print("why is it null?");
    16.     }
    17. }
    While I collide with an other object the print message will be called 4 times. But why can the rigidbody be null? I initialize it on Start and never remove the rigidbody.

    Using Unity version 2017.3.1
     
    Last edited by a moderator: Mar 27, 2018
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    Do you have a rigidbody on the object that has this script on it?
     
  3. Manato

    Manato

    Joined:
    Jun 11, 2015
    Posts:
    28
    Yes, and a collider, too.
     
  4. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    Are you sure you're not using this script on multiple objects without rigidbodies?
     
  5. Manato

    Manato

    Joined:
    Jun 11, 2015
    Posts:
    28
    Try it your self. The OnCollisionEnter Callback will be called 4 times. One time the body is not null the other it is.

    EDIT: Never mind, restarted the editor and the error is away.