-1

Unity is saying "Object reference not set to an instance of an object" on line 23 even though the object is referenced and VS can't find any issues with my code. This is my first time using the C# getters/setters and I don't know what I'm doing wrong. Unity only has problems with line 23 (sprite.sprite = full) and has no problems with anything else

using UnityEngine;

public class Bar : MonoBehaviour {

    public Sprite super;
    public Sprite full;
    public Sprite half;
    public Sprite empty;
    public BarState defaultState = BarState.Full;
    
    private BarState _state;
    private SpriteRenderer sprite;

    public BarState State {
        get {return _state;}
        set {
            switch(value) {
                case BarState.Super:
                    sprite.sprite = super;
                    break;
                case BarState.Full:
                    sprite.sprite = full;
                    break;
                case BarState.Half:
                    sprite.sprite = half;
                    break;
                case BarState.Empty:
                    sprite.sprite = empty;
                    break;
            }
        _state = value;
        }
    }

    void Start() {
        State = defaultState;
        sprite = gameObject.GetComponent<SpriteRenderer>();
    }

}

public enum BarState {
    Super,
    Full,
    Half,
    Empty
}
  • *`even though the object is referenced`* thats not what the error message says. Suggested reading: [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Ňɏssa Pøngjǣrdenlarp Jul 08 '22 at 03:47

1 Answers1

0

You have to swap the lines in your Start() method.

void Start() {
    sprite = gameObject.GetComponent<SpriteRenderer>();
    State = defaultState;
}

This is because when the code State = defaultState is read, then it matches the switch case BarState.Full. In that case, you are assigning the sprite renderer's sprite to a sprite but you didn't reference the sprite renderer yet. Hence, you get the reference to the sprite renderer first and then set the State

Geeky Quentin
  • 2,469
  • 2
  • 7
  • 28