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.
  2. Dismiss Notice

Help with Null Reference Error?

Discussion in 'Scripting' started by deen0_, Jan 8, 2022.

  1. deen0_

    deen0_

    Joined:
    Feb 10, 2021
    Posts:
    33
    Hello, how are you guys?

    I seem to be getting a null reference error I can't figure out. It seems to be in my PlayerLocomotion script where I try and print out my movementInput?

    The inspector correctly shows values for the movementInput, so I know that works, but the PlayerLocomotion script won't read it for some reason. (It reads the full inputManager as null).

    I have attached the scripts (they are short) and a picture of the inspector.

    Please let me know if there is anything you guys see wrong, and thank you.

    Handling Input:
    Code (CSharp):
    1. public class InputManager : MonoBehaviour
    2. {
    3.     PlayerControls playerControls;
    4.  
    5.     public Vector2 movementInput = Vector2.zero;
    6.     public Vector2 rotationInput = Vector2.zero;
    7.  
    8.     private void Awake()
    9.     {
    10.         playerControls = new PlayerControls();
    11.  
    12.         playerControls.Locomotion.Movement.performed += ctx => movementInput = ctx.ReadValue<Vector2>();
    13.         playerControls.Locomotion.Movement.canceled += _ => movementInput = Vector2.zero;
    14.  
    15.         playerControls.Locomotion.Rotation.performed += ctx => rotationInput = ctx.ReadValue<Vector2>();
    16.         playerControls.Locomotion.Rotation.canceled += _ => rotationInput = Vector2.zero;
    17.     }
    18.  
    19.     private void OnEnable() => playerControls.Enable();
    20.  
    21.     private void OnDisable() => playerControls.Disable();
    22. }
    PlayerLocomotion (where error occurs Line 32+):
    Code (CSharp):
    1. public class PlayerLocomotion : MonoBehaviour
    2. {
    3.     [Header("Movement Stats")]
    4.     public float moveSpeed = 5f;
    5.     [SerializeField] float rotationSpeed = 15f;
    6.  
    7.  
    8.     [Header("Addit.")]
    9.     [SerializeField] Transform cameraObject;
    10.     Vector3 moveDirection;
    11.  
    12.     //float speed = rb.velocity.magnitude;
    13.  
    14.  
    15.     [SerializeField] InputManager inputManager;
    16.     Rigidbody rb;
    17.  
    18.     private void Awake()
    19.     {
    20.         inputManager = GetComponent<InputManager>();
    21.         rb = GetComponent<Rigidbody>();
    22.     }
    23.  
    24.  
    25.     private void Movement()
    26.     {
    27.         //if (inputManager == null) { Debug.Log(gameObject.name + " doesn't have an InputManager"); }
    28.         Debug.Log(inputManager); // Prints Null
    29.         moveDirection = (cameraObject.right * inputManager.movementInput.x) + (cameraObject.forward * inputManager.movementInput.y);
    30.         moveDirection.Normalize();
    31.         moveDirection.y = 0f;
    32.  
    33.         Vector3 moveVelocity;
    34.  
    35.         moveVelocity = moveDirection * moveSpeed;
    36.  
    37.         rb.velocity = moveVelocity;
    38.     }
    39.  
    40.  
    41.     public void HandleAllLocomotion()
    42.     {
    43.         Movement();
    44.         //Rotation();
    45.     }
    46.  
    47.  
    48.     private void Rotation() // Purely player rotation, not camera
    49.     {
    50.         Vector3 targetDirection = Vector3.zero;
    51.  
    52.         targetDirection = cameraObject.right * inputManager.movementInput.x + cameraObject.forward * inputManager.movementInput.y;
    53.         targetDirection.Normalize();
    54.         targetDirection.y = 0;
    55.  
    56.         Quaternion targetRotation = Quaternion.LookRotation(targetDirection);
    57.         Quaternion playerRotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
    58.  
    59.         transform.rotation = playerRotation;
    60.     }
    61. }
    PlayerManager (where scripts are called):
    Code (CSharp):
    1. public class PlayerManager : MonoBehaviour
    2. {
    3.  
    4.     PlayerLocomotion playerLocomotion;
    5.     private void Awake()
    6.     {
    7.         playerLocomotion = new PlayerLocomotion();
    8.     }
    9.  
    10.     // Update is called once per frame
    11.     private void Update()
    12.     {
    13.      
    14.     }
    15.  
    16.     private void FixedUpdate()
    17.     {
    18.         playerLocomotion.HandleAllLocomotion();
    19.     }
    20. }
     

    Attached Files:

    Last edited: Jan 8, 2022
  2. Deleted User

    Deleted User

    Guest

    You uploaded scripts instead of posting them using code tags.
    Code (csharp):
    1.  public string like = "this";
    Most people will not go through the effort of downloading your files.

    Also, try not to double-post. Edit your original post if you're not replying to another user. You might be seen as spamming or trying to bump your post (which is still spam). I doubt those are your intentions but it's forum etiquette.
     
    Last edited by a moderator: Jan 8, 2022
  3. deen0_

    deen0_

    Joined:
    Feb 10, 2021
    Posts:
    33
    Sorry about that, wasn't sure about full scripts, I fixed it up.

    Thanks for telling me.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,767
    There's still only one way with three steps to fix a Null Reference Error. Here are the steps:

    - Identify what is null
    - Identify why it is null
    - Fix that.


    NOTE: None of the steps are "figure it out."

    The answer is always the same... ALWAYS. It is the single most common error ever.

    Don't waste your life spinning around and round on this error. Instead, learn how to fix it fast... it's EASY!!

    Some notes on how to fix a NullReferenceException error in Unity3D
    - also known as: Unassigned Reference Exception
    - also known as: Missing Reference Exception
    - also known as: Object reference not set to an instance of an object

    http://plbm.com/?p=221

    The basic steps outlined above are:
    - Identify what is null
    - Identify why it is null
    - Fix that.

    Expect to see this error a LOT. It's easily the most common thing to do when working. Learn how to fix it rapidly. It's easy. See the above link for more tips.

    You need to figure out HOW that variable is supposed to get its initial value. There are many ways in Unity. In order of likelihood, it might be ONE of the following:

    - drag it in using the inspector
    - code inside this script initializes it
    - some OTHER external code initializes it
    - ? something else?

    This is the kind of mindset and thinking process you need to bring to this problem:

    https://forum.unity.com/threads/why-do-my-music-ignore-the-sliders.993849/#post-6453695

    Step by step, break it down, find the problem.

    Here is a clean analogy of the actual underlying problem of a null reference exception:

    https://forum.unity.com/threads/nul...n-instance-of-an-object.1108865/#post-7137032
     
  5. deen0_

    deen0_

    Joined:
    Feb 10, 2021
    Posts:
    33

    Okay, thank you.

    What is null is the inputManager reference, therefore the movementInput defined in that script won't read in my other script.

    It is initialized by:
    InputManager inputManager;
    and within Awake()
    inputManager = GetComponent<InputManager>();
    . I also manually inserted the script within the inspector, however the same 'null' issue occurs.

    I can't seem to understand why it returns null? I checked the scene for any other gameobjects with this script, however it is the only one, so that shouldn't be an issue. Besides I manually inserted it, which would've gotten rid of that issue.

    Ive seemed to hit a little wall on this for the past couple hours, and would really appreciate any further help/explanation.
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,767
    This being marked as serialized:

    Is directly conflicting with this:

    You can either drag it in (in which case keep the SerializeField and REMOVE the Getcomponent), or you can use GetComponent, assuming it is located on this same GameObject.

    As I wrote above, make sure you are doing only ONE of the following methods of initializing it.

    You have two ways of initializing that field going on here.

    Only one will win and looks like it's not the one you want.
     
  7. deen0_

    deen0_

    Joined:
    Feb 10, 2021
    Posts:
    33
    I got rid of the [SerializeField], and kept the incode reference, however I still get the same error. The [SerializeField] was mostly to let me see in the inspector, to make sure the script was really there.

    Also tried the other way (no Awake, instead dragged in inspector), and the null still appeared.
     
  8. Deleted User

    Deleted User

    Guest

  9. deen0_

    deen0_

    Joined:
    Feb 10, 2021
    Posts:
    33
    Yes, they are all on the same gameobject.

    & fixed, thank you
     

    Attached Files:

  10. Deleted User

    Deleted User

    Guest

    Just to clarify...

    Consider a player gameobject with a PlayerControl.cs script attached to it.

    gameObject.GetComponent<Rigidbody>() is like saying "get the rigidbody component from the gameobject this script is attached to"

    Otherwise you need to get a reference first.

    Code (csharp):
    1.  
    2.  
    3. public GameObject publicExample;
    4. private GameObject _privateExample;
    5.  
    6. void Start()
    7. {
    8.     _privateExample = GameObject.FindWithTag("Player");
    9.  
    10.     // Get the Rigidbody of gameobject publicExample.
    11.     Rigidbody example1 = publicExample.GetComponent<Rigidbody>();
    12.  
    13.     // Get the Rigidbody of gameobject _privateExample.
    14.     Rigidbody example2 = _privateExample.GetComponent<Rigidbody>();
    15.  
    16.     // Get the Rigidbody of the gameobject this script is attached to.
    17.     Rigidbody example3 = gameObject.GetComponent<Rigidbody>();
    18. }
    19.  
    20.  
     
    Last edited by a moderator: Jan 8, 2022
  11. deen0_

    deen0_

    Joined:
    Feb 10, 2021
    Posts:
    33
    I figured out the problem, in my function which called everything, I accidentally called a monobehavior function using 'new'
     
    Deleted User likes this.
  12. Deleted User

    Deleted User

    Guest

    upload_2022-1-8_20-3-54.jpeg
     
    Kurt-Dekker likes this.