Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

When to use public or private variables in unity3d?


Asked by Mia Caldwell on Dec 14, 2021 FAQ



When declaring a new variable, keep it private by default, unless you expect to refrence it from another class. Then, after your code is written, add [SerializeField] and [HideInInspector] if necessary to achieve the desired appearance of the component in the Inspector.
Keeping this in consideration,
Generally speaking, it’s good practice to only make a variable public if other scripts need to access it and, if they don’t, to keep it private. If, however, other scripts do not need to access it, but you do need to see it in the inspector then you can use Serialize Field instead.
In respect to this, In the context of Unity, public fields are displayed in the inspector, so if you attach the Player component to a GameObject, the Health field will be visible and you will be able to edit it in the Inspector. If the field is private, you will not see it in the Inspector.
Consequently,
Var is not recommended because it can make the code confusing. As for public variables, the only issue is that they are exposed in the inspector, I would advise you only make variables public that really need to be. Is this recommended or in Unity's case is just making variables public ok?
Additionally,
How to access a variable from another script in Unity. To access a variable from another script you’ll first need to get a reference to whatever type of object, ... That way other scripts can access the Singleton, and its variables, without getting a reference to it first.