Search Unity

Question Null Reference!

Discussion in 'Scripting' started by Sandesh321, Jun 28, 2021.

  1. Sandesh321

    Sandesh321

    Joined:
    May 2, 2021
    Posts:
    55
    Hi, I keep getting null reference on this code! The funny thing is, it was working fine unity today morning, and when I tired playing it later without changing any code, it now throws a null reference. I have stated the variable/value in update, and then updated the slider value in late update, but it still throws a null reference. I have tried different ways, but it doesn't work.
    Code (CSharp):
    1. public Slider HealthSlider;
    2.     [HideInInspector]
    3.     public float Health;
    4.     private GameObject Warden;
    5.     public  BlightBehaviours BlightBehaviours;
    6.     void Start()
    7.     {
    8.         Warden = GameObject.Find("BlightWarden");
    9.     }
    10.     private void Update()
    11.     {
    12.      
    13.    
    14.         Health = BlightBehaviours.Hitpoints;
    15.  
    16.     }
    17.  
    18.     // Update is called once per frame
    19.     void LateUpdate()
    20.     {
    21.         HealthSlider.value = Health; // this part throws a null reference, it was working fine before!
    22.  
    23.  
    24.  
    25.     }
    26.     public void DestroySlider()
    27.     {
    28.         Destroy(gameObject);
    29.     }
     
  2. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Ensure that HealthSlider has been assigned in the inspector.

    Also check that you haven't accidentally added a second copy of your script somewhere (search t:<scriptname>) in the hierarchy search.
     
  3. Sandesh321

    Sandesh321

    Joined:
    May 2, 2021
    Posts:
    55
    I have checked that HealthSlider is in the correct place and there is no duplicate script, but it still throws a null reference exception :|
     
  4. Sandesh321

    Sandesh321

    Joined:
    May 2, 2021
    Posts:
    55
    I literally did nothing and it works again! ???? Do you know why ??