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

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

Discussion in 'Scripting' started by SHjiwani, Sep 1, 2023.

  1. SHjiwani

    SHjiwani

    Joined:
    Aug 25, 2023
    Posts:
    5
    I'm making a game and I'm currently working on the message to show that the player won when their score gets high enough, but for some reason I'm getting an error and the message isn't showing up. I've been stuck on this for like a week and I'm not sure how to solve this.

    The error I'm getting is:

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

    PlayerController.SetCountText () (at Assets/Scripts 1/PlayerController.cs:48)



    I'm almost certain it is because I am refernceing a game object in one script from another one but I don't know exactly what the issue is or how to solve it.

    The first script is PlayerController script where the error is coming from and the second is where the winTextObject is.



    Here is the first:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.InputSystem;
    5. using TMPro;
    6. using UnityEngine.SceneManagement;
    7.  
    8. public class PlayerController : MonoBehaviour
    9. {
    10.     public float speed = 0;
    11.     public TextMeshProUGUI countText;
    12.     public Timer timer;
    13.  
    14.     private Rigidbody rb;
    15.     public int count;
    16.     private float movementX;
    17.     private float movementY;
    18.  
    19.    
    20.      // Start is called before the first frame update
    21.     void Start()
    22.     {
    23.         rb = GetComponent<Rigidbody>();
    24.         count = 0;
    25.  
    26.         SetCountText();
    27.        
    28.         timer.winTextObject.SetActive(false);      
    29.     }
    30.  
    31.     void OnMove(InputValue movementValue)
    32.     {
    33.        Vector2 movementVector = movementValue.Get<Vector2>();
    34.  
    35.        movementX = movementVector.x;
    36.        movementY = movementVector.y;
    37.     }
    38.  
    39.     void SetCountText()
    40.     {
    41.         countText.text = "Count: " + count.ToString();
    42.        
    43.        
    44.        
    45.         if(count == 40)
    46.         {
    47.             timer.winTextObject.SetActive(true);
    48.         }
    49.     }
    50.  
    51.     void FixedUpdate()
    52.     {
    53.         Vector3 movement = new Vector3(movementX, 0.0f, movementY);
    54.  
    55.         rb.AddForce(movement * speed);
    56.  
    57.        
    58.     }
    59.  
    60.     private void OnTriggerEnter(Collider other)
    61.     {
    62.         if(other.gameObject.CompareTag("PickUp"))
    63.         {
    64.             other.gameObject.SetActive(false);
    65.             count = count + 1;
    66.  
    67.             SetCountText();
    68.         }
    69.  
    70.        
    71.         if (count == 10)
    72.         {
    73.             if (other.tag == "LevelExit")
    74.             {
    75.                 SceneManager.LoadScene(1);
    76.             }
    77.         }
    78.  
    79.         if (count == 40)
    80.         {
    81.             if (other.tag == "LevelExit")
    82.             {
    83.                 SceneManager.LoadScene(2);
    84.             }
    85.         }
    86.     }
    87. }
    88.  
    And the Second:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using TMPro;
    5.  
    6. public class Timer : MonoBehaviour
    7. {
    8.     public PlayerController playerController;
    9.    
    10.     public GameObject loseTextObject;
    11.     public GameObject winTextObject;
    12.    
    13.     [Header("Component")]
    14.     public TextMeshProUGUI timerText;
    15.  
    16.     [Header("Timer Settings")]
    17.     public float currentTime;
    18.     public bool countDown;
    19.  
    20.     [Header("Limit Settings")]
    21.     public bool hasLimit;
    22.     public float timerLimit;
    23.  
    24.     [Header("Format Settings")]
    25.     public bool hasFormat;
    26.     public TimerFormats format;
    27.     private Dictionary<TimerFormats, string> timeFormats = new Dictionary<TimerFormats, string>();
    28.  
    29.     // Start is called before the first frame update
    30.     void Start()
    31.     {
    32.         timeFormats.Add(TimerFormats.Whole, "0");
    33.         timeFormats.Add(TimerFormats.TenthDecimal, "0.0");
    34.         timeFormats.Add(TimerFormats.HundrethsDecimal, "0.00");
    35.         timeFormats.Add(TimerFormats.ThousanthsDecimal, "0.000");
    36.  
    37.         loseTextObject.SetActive(false);
    38.     }
    39.  
    40.     // Update is called once per frame
    41.     void Update()
    42.     {
    43.         currentTime = countDown ? currentTime -= Time.deltaTime : currentTime += Time.deltaTime;
    44.  
    45.         if(hasLimit && ((countDown && currentTime <= timerLimit) || (!countDown && currentTime >= timerLimit)))
    46.         {
    47.             currentTime = timerLimit;
    48.             SetTimerText();
    49.             timerText.color = Color.red;
    50.             enabled = false;
    51.         }
    52.  
    53.         if(timerText.Equals("0.00") && playerController.count < 40)
    54.         {
    55.             loseTextObject.SetActive(true);
    56.         }
    57.  
    58.         SetTimerText();
    59.     }
    60.  
    61.     private void SetTimerText()
    62.     {
    63.         timerText.text = hasFormat ? currentTime.ToString(timeFormats[format]) : currentTime.ToString();
    64.     }
    65. }
    66.  
    67. public enum TimerFormats
    68. {
    69.     Whole,
    70.     TenthDecimal,
    71.     HundrethsDecimal,
    72.     ThousanthsDecimal
    73. }
    74.  
     
  2. bugfinders

    bugfinders

    Joined:
    Jul 5, 2018
    Posts:
    711
    The error doesnt lie
    Look at the line, workout whats null
    fix it.

    it is no more hard than that
     
  3. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    It is difficult when the error points to the end of a method:
    Code (CSharp):
    1. if(count == 40)
    2.         {
    3.             timer.winTextObject.SetActive(true);
    4.         } //<--- compile error
    So you have to look into that method and see where it can mess up, or debug by doing something like this:
    Code (CSharp):
    1. if(count == 40)
    2. {
    3.     if (timer.winTextObject == null)
    4.     {
    5.         print("timer winTextObject does not exist right now!!!");
    6.     }
    7.     else
    8.     {
    9.         timer.winTextObject.SetActive(true);
    10.     }
    11. }
    So... like Kurt says, "When in doubt, print it out!". :)
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    Yoop... thanks Wide!

    The answer is always the same... ALWAYS!

    How to fix a NullReferenceException error

    https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

    Three steps to success:
    - Identify what is null <-- any other action taken before this step is WASTED TIME
    - Identify why it is null
    - Fix that