Unity array null reference. I switched to list but how can i remove the element when the gameObject is destroyed? Jun 20, 2014 · Whenever Unity throws you an exception they also state the script name and the line number where the exception is happening. private Item newItem; for(i=0; i<4; i++) { newItem = new Item(); X[i] = newItem; //do extra stuff with newItem if needed } NullReferenceException when accessing variables in a 2D array in Unity Ask Question Asked 14 years, 3 months ago Modified 8 years, 1 month ago Null Reference Exceptions A NullReferenceException happens when you try to access a reference variable that doesn’t reference any object. This is why you are getting a NullReferenceException when you try to access the property of one of the array elements. In some situations, simply ignoring null references can break our code. May 27, 2015 · You’re array is properly initialized (x = new items [4]) but at that point you still only have an array with space for 4 of your items. When you try to access a reference variable that doesn’t reference an object, the reference type defaults to null and Unity returns a NullReferenceException. Null Reference Exceptions A NullReferenceException happens when you try to access a reference variable that doesn’t reference any object. Put the following in your start-function and try it. Eat the cookie. I am using the following method for swapping/moving item in the inventory Array : public class ItemSlot { [SerializeField] public string ItemName; [SerializeField] public ItemsSO ItemProperty; [SerializeField Sep 8, 2025 · Learn how to prevent (and fix) Null Reference Exceptions in Unity with advanced lifecycle tips, debugging workflows, and real-world case studies.