Search Unity

Fixed,tx - NullReferenceException in a simple code

Discussion in 'Editor & General Support' started by profGumidek, Oct 18, 2019.

  1. profGumidek

    profGumidek

    Joined:
    Aug 29, 2019
    Posts:
    9
    Hey everyone,
    after trying to find out what is wrong for more than two days I need to ask.

    Code (CSharp):
    1. public class CharacterStats:MonoBehaviour
    2. {
    3.  
    4.   public float maxHealth = 10.0f;
    5.   public float health = 10.0f;
    6.   public Slider healthSlider;
    7.  
    8.     void Awake()
    9.     {
    10.             Debug.Log(healthSlider.name);
    11.     }
    I have the Slider component added in editor
    upload_2019-10-18_16-34-39.png

    but I still get an error:
    NullReferenceException: Object reference not set to an instance of an object
    CharacterStats.Awake () (at Assets/Scripts/CaracterLogic/CharacterStats.cs:18)

    And whats weird on it? I can work with the Slider component. The code I

    Code (CSharp):
    1.        
    2.     private void OnGUI()
    3.     {
    4.         healthSlider.value = health / maxHealth;
    5.     }
    6.  
    7.  
    does what is should (health is decresing as it should) and does not throw the error. But when I try to remove the debug log from aware fuction, it is thorown in the OnGUI.

    My guess is that I must have broken the project somehow but I have no idea how to fix it.

    Please help!

    Thanks
     
  2. profGumidek

    profGumidek

    Joined:
    Aug 29, 2019
    Posts:
    9
    OK, im a noob and found out that the script was on my enemy.. sry ppl