- Home /
How do I assign a prefab reference to a private variable?
private GameObject myPrefab;
I need to assign a prefab reference to this variable, but because Unity uses public and private to indicate what to show and make editable in the inspector, this ends up being quite a problem:
I can't reference prefabs from the Assets folder in code.
I can't manually drag the prefab reference onto the script in the inspector as the variable is private.
I suppose I COULD just make it public but that'd be horrible programming practice making a variable that shouldn't be accessible from the outside public instead of private, just so I can actually initialize the thing.. Not to mention even if I did add it as a new public variable, all my derived classes don't get updated with the new value, so I'd have to go through each instance of a derived class individually and click reset (if there's a quicker way to handle that, I'd really like to know).
I also don't want to use Resources.Load as then I'd have to pass in strings of the prefab names instead of actual references, which is a huge problem if I ever decide to rename some prefabs which I most likely will.
I can kind of see why Unity uses public and private by default to determine what to show in the inspector, but how do I override this behaviour? How do I manually tell it what variables to expose or hide regardless of whether or not they happen to be public or private? As it is, this automatic variable hiding feature is limiting what I'd otherwise be able to do, at least with private variables.
Answer by Arkuni · Aug 23, 2014 at 09:24 PM
The answer you seek, is the SerializeField attribute:
[SerializeField]
private GameObject myPrefab;
This attribute will tell Unity to serialize the field, which means that the value will be saved when going into Play-Mode. It will also make the field popup in the editor.
Awesome, now the private field shows up in the inspector, but it still doesn't keep the value consistent among all derived classes. How do I update the value for all derived classes? Hitting reset on each individual instance of a derived component is just not an option.. Is there like, a reset all button somewhere?