I have this class, a simple MonoBehaviour. and it has a public array.
I need for it to be null. but an empty array 0 length array always pop up during runtime.
I tried array = null, but prefab seem to disagree with me when it create a new instance.
did I accidentally serialize some default value into the prefab?
but removing array from the editor isn’t possible since there is no option for null.
or is it because public variable are always serialized and it cannot be null?
I don’t know, if anyone know this behavior of the editor, pls give me some clue.
my solution now is to add array.GetLength(0)<1 to catch these weird empty array.
but it still strike me as bad coding, if anyone has a better solution pls help!
Null just means it doesn’t exist. When you declare your public array you are making a zero length array ready to do your bidding. But it is a zero length array— it is not nothing! The question is, if you need an array to be null (nothing), why do you have it to begin with?
Perhaps a solution is to remove the array from your script and then only create one in a function when you need it. I think it’d be easier to help you if we knew what you were doing with this array and why you think you need it to be ‘null’.
i set it as null during initialization. check the constructor “if array==null” and it return true, but when the object is cloned, it is no longer null. afaik, zero length array isn’t nothing, it still take up memory which is why i intentionally use null.
this is important because the object is intended to build the array on the fly, if it thinks there is an array, it will not create a new array. the array can be remove (set to null) to inform the game that it need to make a new array. it has to stay in memory because it function as a lookup table, if it is null, the code will search for it directly instead and build a new array after finding it.
I have a similar problem, I need to implement a system in which there are characters with items and items can also contain character. But for this, I don’t need the variables to be infinitely initialized, because this causes looping and Unity freezes.
[System.Serializable]
public class Item
{
int id;
Character mob;
}
public class Character
{
int name;
Item charInventory;
}
Though the reserialisation happens as a result of instantiating the game object. If you want to ensure Unity doesn’t soft-serialise stuff, it needs to be decorated with [System.NonSerialized].
Unity’s default serialisation does not support null. If you want to support null, that’s where [SerializeReference] is needed to allow null values. You may need to make custom inspector stuff to allow this.