问题
When should I use public, private, or [SerializeField]? which is the most practical?
回答1:
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.
来源:https://stackoverflow.com/questions/52906797/when-should-i-use-public-private-or-serializefield-unity-c-sharp