Hurry over to any C# code example for how to correctly initialize arrays.
ALSO, initialize the array in Start(), otherwise Unity’s serialization might wipe out your coded 6 size.
Here’s why:
Serialized / public fields in Unity are initialized as a cascade of possible values, each subsequent value (if present) overwriting the previous value:
-
what the class constructor makes (either default(T) or else field initializers, eg “what’s in your code”)
-
what may be saved with the prefab
-
what may be saved with the prefab override(s)/variant(s)
-
what may be saved in the scene and not applied to the prefab
-
what may be changed in the scene and not yet saved to disk
-
what may be changed in OnEnable(), Awake(), Start(), or even later
Make sure you only initialize things at ONE of the above levels, or if necessary, at levels that you specifically understand in your use case. Otherwise errors will seem very mysterious.
Here’s the official discussion: Serialization in Unity
If you must initialize fields, then do so in the void Reset() method, which ONLY runs in the UnityEditor.
Here’s more nitty-gritty on serialization:
Field initializers versus using Reset() function and Unity serialization:
To avoid complexity in your prefabs / scenes, I recommend NEVER using the FormerlySerializedAsAttribute
Thanks so much for the help. I’ve moved it into the start function but I’m not sure I understood what you said about serialization. Do you think you could display a proper example of how I should lay this out?
Ideally make that array field private.
Otherwise, if your code is always jamming those X number of specific objects into that array, AND you want external (public) access, make it a property, then allocate it in Start().
public GameObject[] mylist { get; private set; }
// and then in Start() just initialize it:
mylist = new GameObject[] { a,b,c,d};
If you had actually posted the code properly I could have copy/pasted and modified it so it just dropped in as if it was your code above, but I’m not retyping your code. ![]()
NOTE: you might want to look into ScriptableObjects… they are perfect for making these sorts of pre-authored data sets, such as the list of attacks.
Here’s some ScriptableObject scribblings:
ScriptableObject usage in RPGs:
Usage as a shared common data container:
