Search Unity

Object Reference Not Set to Instance of An Object

Discussion in 'Scripting' started by Ant85, Jan 9, 2020.

  1. Ant85

    Ant85

    Joined:
    Sep 30, 2018
    Posts:
    6
    I am fairly new to unity, so I am using one of unity's tutorial projects, karting. I am getting a NullReferenceException error after adding multiplayer into the game using pun 2.

    This is the exact error:

    NullReferenceException: Object reference not set to an instance of an object
    KartGame.KartSystems.KartMovement.get_LocalSpeed () (at Assets/Karting/Scripts/KartSystems/KartMovement/KartMovement.cs:109)
    KartGame.KartSystems.EngineAudio.Update () (at Assets/Karting/Scripts/KartSystems/KartAudio/EngineAudio.cs:67)

    The two lines it points to are
    Code (CSharp):
    1. public float LocalSpeed => (Quaternion.Inverse (m_Rigidbody.rotation) * Quaternion.Inverse (m_DriftOffset) * m_Velocity).z;
    and
    Code (CSharp):
    1. RPM = m_KartInfo.LocalSpeed / m_KartInfo.CurrentStats.topSpeed;
    Any help would be greatly appreciated!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,686
    You can't initialize class-level variables with objects such as m_Rigidbody, because they don't (necessarily) exist at constructor time.

    Put the intializer into either
    Awake()
    or
    Start()
    instead. It's a necessary pattern in Unity because the constructor code is not run on the main thread, and hence does not have access to mainline Unity stuff, even if it did already exist.

    Monobehaviors have a very specific lifecycle and you can read more about it here:

    https://docs.unity3d.com/Manual/ExecutionOrder.html