Public and Private are access modifiers, they’re used to determine if other classes are able to access a variable.
- Public variables are accessible from outside of the class they’re declared in
- Private variables are not accessible from outside of the class
The access modifier is added as a keyword before the variable type and, if neither is used, the variable will be private by default.
Here’s what it looks like in code:
public float publicFloat; // Public
private string privateFloat; // Private
int privateInteger; // Private
Public variables are also serialised, which means that they will show up in the Inspector. However, if you’re only making a variable public so that you can see it in the Inspector, then you can do this by Serializing it instead.
Like this:
[SerializeField] float playerHealth; // Private, but will show in the Inspector
The point of using Serialize Field is to show the variable in the Inspector, but without giving other scripts any access to it. As a rule of thumb, it’s usually better to use serialized variables instead of public ones, as it prevents you from giving scripts access to variables they don’t need.
It’s also possible to make a variable available to other scripts without showing it in the Inspector.
Like this:
// This will not show in the inspector
[HideInInspector]
public float playerHealth; // Public, but won't show in the Inspector
This can be useful when you do need to keep a variable public, but you don’t need to see it, keeping your Inspector more organised and less cluttered.
Other access modifiers include Protected, which allows an inheriting class to access a variable but not other classes.
See also: