Search Unity

Rigidbody not working?

Discussion in 'Physics' started by GreenBaguette, Jan 18, 2020.

  1. GreenBaguette

    GreenBaguette

    Joined:
    Jan 8, 2020
    Posts:
    3
    I've attached my CarController script to a Car prefab. The car has a Rigidbody added by the "Add component" thanks to the inspector menu.

    But it seems I cannot access the value of any attributes of the Rigidbody in my script.

    Code (CSharp):
    1.  
    2.    private Rigidbody m_Rigidbody;
    3.    void Start()
    4.     {
    5.         m_Rigidbody = GetComponent<Rigidbody>();
    6.     }
    7.  
    8.     void Update()
    9.     {
    10.         if (m_Rigidbody.velocity > 5)
    11.         {
    12.             //Do stuff
    13.         }
    14.     }
    > NullReferenceException: Object reference not set to an instance of an object
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,500
    Because you don't post the full error message I'd have to guess that the error is reported on Line 10. This is because the GameObject that this script is on doesn't have a Rigidbody on it so "m_Rigidbody" is null.
     
  3. GreenBaguette

    GreenBaguette

    Joined:
    Jan 8, 2020
    Posts:
    3
    Sorry I didn't want to flood the post with 100 lines of code...

    Yes it is on line 10.

    How come it's null, since my GameObject/prefab has one?

    Here is what I have in my GameObject inspector.

    If you want the full code, I can upload it if you want.
     

    Attached Files:

  4. GreenBaguette

    GreenBaguette

    Joined:
    Jan 8, 2020
    Posts:
    3
    I think the problem is not this. The Rigidbody is good, but it's link to the logic of my game.

    I'm using a python client to spawn a Car, so I used a Mains Thread Dispatcher to Instantiate Cars in Threads. And I think o'm not very Thread Safe on what i'm doing.

    Thanks anyway :)
     
    MelvMay likes this.