Search Unity

NullReferenceException: Object reference not set to an instance of an object

Discussion in 'Scripting' started by MikawasakiDigital, Apr 21, 2019.

  1. MikawasakiDigital

    MikawasakiDigital

    Joined:
    Mar 29, 2019
    Posts:
    95
    Please, if anyone could give some insight on what could be done to resolve this issue.

    Error reads

    14:12:12 NullReferenceException: Object reference not set to an instance of an object BillboardUi.LookAtPlayer () (at Assets/Scripts/Billboard.cs:20)

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class BillboardUi : MonoBehaviour
    6. {
    7.     private Camera playerCamera;
    8.  
    9.     private void Start()
    10.     {
    11.         playerCamera = Camera.main;
    12.     }
    13.  
    14.     private void FixedUpdate()
    15.     {
    16.         LookAtPlayer();
    17.     }
    18.  
    19.     private void LookAtPlayer()
    20.     {
    21.         transform.LookAt(transform.position + playerCamera.transform.rotation * Vector3.forward, playerCamera.transform.rotation * Vector3.up);
    22.     }
    23. }
    24.  
     
  2. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    Add this to the start function: "Debug.Log(playerCamera.transform)", it will tell you if playerCamera is null.

    it will only find Camera.main if the camera is tagged with the tag MainCamera.

    BTW, Don't use fixed update unless you need it (it's for physics stuff), use the normal Update().
     
    MikawasakiDigital likes this.
  3. MikawasakiDigital

    MikawasakiDigital

    Joined:
    Mar 29, 2019
    Posts:
    95
    I had not tagged the camera as MainCamera.

    That was exactly the issue.

    BTW thanks for the tip on using void updates!

    It made a lot of sense.

    Great hearing from you again, stay well brotha. :D