Hard coding an array of prefabs

You are initializing it with primitives, in this case integers.

Nobody else is needed to be around to make this data:

That is just integers. I can make them, you can make them, Spiney can make them, my dog can probably make them, and for sure, the C# compilers can all make them and fill out your array.

Your question was entitled “Hard coding an array of prefabs.”

Prefabs are GameObjects.

GameObjects are NOT primitive data types.

They’re not even what we call a POCO, or Plain Old C# Object.

GameObjects, along with anything derived from UnityEngine.Object, are very special hybrid C# and C++ engine side objects.

You can’t make them. I can’t make them. Spiney is resourceful enough they might be able to do it. My dog? No way.

The ONLY PERSON on this planet that can make GameObjects is Unity.

If you think you’re making a GameObject, you’re not. You’re asking Unity make it for you.

The compiler can’t make GameObjects either, nor does it know how to ask Unity make GameObjects for it at compile time.

But then in the end the code you showed is a Dictionary containing int, hashed by string. Those CAN be made by the compiler.

If you saw order change, most likely it was something else, another bug.

It might also be due to not fully grasping the serialization system in Unity and how it works.

Here’s some light reading about that and how it can be very confusing if you use field initializers such as your integers above:

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: https://blog.unity.com/technology/serialization-in-unity

If you must initialize fields, then do so in the void Reset() method, which ONLY runs in the UnityEditor.

Field initializers versus using Reset() function and Unity serialization:

https://discussions.unity.com/t/829681/2

https://discussions.unity.com/t/846251/8

To avoid complexity in your prefabs / scenes, I recommend NEVER using the FormerlySerializedAsAttribute

3 Likes