- Home /
When would I encapsulate variables?
In Unity, we tend to make instance variables public so that we can play with them in the inspector before execution. By doing so, we nullify the practice of encapsulating private instance variables as we are forced to make them public. Should I make everything that should be available to other classes public to maintain consistency? When do I encapsulate? When don't I? Is there anything wrong with making everything public (that other classes will use)?
Answer by TreyH · Jun 15, 2018 at 10:58 AM
Well, whenever you want to. It's not likely that the only variables in your game will be attached to MonoBehaviours, so your actual question seems to be "When would I encapsulate with a MonoBehaviour".
And for that, a variable doesn't need to be public for you to access it in the inspector. Public, serializable variables will be exposed by default, but you can tell Unity to expose private variables with the following syntax:
[SerializeField]
private int testMe = 0;
It gets a little more complicated than this, as the Vector3 and Quaternion objects are not serializable by default but are exposed in the inspector. I assume this is because these objects have CustomPropertyDrawers defined already within Unity, but someone more knowledgeable can chime in to verify that.
This answer contains all the necessary information. I would just add that in my opinion (and experience) you should always* encapsulate variables.
*always meaning there are very few exceptions
Answer by Captain_Pineapple · Jun 15, 2018 at 10:51 AM
Hey there,
take a look at SerializeField. This might be the thing for you to go by and programm by the conventions you are used to if i understand this correctly.