When should I use public, private, or [SerializeField]? Unity C#

二次信任 提交于 2021-01-20 13:53:57

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!