Home > Enterprise >  Unity Object reference not set to an instance of an object with enums
Unity Object reference not set to an instance of an object with enums

Time:07-09

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
}

CodePudding user response:

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

  • Related