0
votes

I'm struggling with this problem for 2 days, I'm trying to add go GameObject into a list changedObjects but i don't know why changedObjects is Null.

I tried this:

public class UndoObject : MonoBehaviour {
    private List<GameObject> changedObjects;

    void Start () {
        changedObjects = new List<GameObject>();
    }

    public void Push(GameObject go) {
        Debug.Log(changedObjects);
        if (go != null) {
            changedObjects.Add(go);
        }
    }

    public List<GameObject> GetAll () {
        return changedObjects;
    }
}

Than I call UndoObject.Push from another class with GameObject.

But, it keep throwing error:

NullReferenceException: Object reference not set to an instance of an object UndoObject.Push (UnityEngine.GameObject go) (at Assets/Standard Assets/Scripts/UndoObject.cs:15) Manager.FixedUpdate () (at Assets/Standard Assets/Scripts/Manager.cs:73)

UndoObject.cs:15 is changedObjects.Add(go);

1
are you calling start() before calling add() ? - Sajeetharan
@Sajeetharan Yes, is that wrong? - user92635438
please post that code too - Sajeetharan
@Sajeetharan The code is right here, that's the whole code i have. Are you asking for code where i called UndoObject.Push? - user92635438
yes, where you call push and start method - Sajeetharan

1 Answers

2
votes

I think you are calling the push method directly without calling start() which will initialize the array, however you can add this inside your push method to make sure array is always initialized.

 public void Push(GameObject go) {
        if (changedObjects == null)
        { 
           changedObjects = new List<GameObject>();
        }
        if (go != null) {
            changedObjects.Add(go);
        }
 }