When should I use public, private, or [SerializeField]? which is the most practical?
When should I use public, private, or [SerializeField]? which is the most practical?
First, you need to make sure you understand the difference between public and private variables. Here's the official documentation for different access modifiers. I strongly recommend you read through it, but a simple version would be that public variables can be referenced by other classes, while private variables cannot.
Imagine if you have a Player class with a Health field. Let's assume that by your design, you want a GameManager class to check the Player's health to determine if the player is alive. If the Health field is public, this is possible by referencing Player.Health
If the Health field is private, it can only be accessed inside the Player class.
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.
There are however cases where you want to have a private field visible in the Inspector or a public field hidden in the inspector. For these purposes we have [SerializeField] and [HideInInspector]. As the names suggest, [SerializeField] can be added before a private field to make it visible in the inspector and [HideInInspector] can be added before a public field to hide it in the inspector.
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.
Doing this on phone so hopefully I get this about right. public gives access to any and all other components to access the variable
private restricts access to the script itself to access it but doesn't mean you can't make it accessible.
[SerializeField] private int hiddenNumber = 101;
public int HiddenNumber
{
get
{
return hiddenNumber;
}
}
This makes the variable accessible from other components but they won't be able to set the variable to anything.
Edit: Forgot to add you can also just do
public int hiddenNumber {get; private set;}
public int HiddenNumber {get; private set;} = 102;