[SerializeField] vs public field

Greetings,

I am noticing that private fields decorated with [SerializeField] are being used over public fields. In the late past (Unity 4) I recall it was always use a public variable. I looked up [SerializeField] when I first encountered it here and see that it allows private variables to be exposed to the Inspector. So is the preference now to use private variables with [SerializeField] so other objects are unable to change those values? Just wondering on this new paradigm.

Thank you,

Brett

1 Like

As I understand it, when a variable is public, it can be accessed by the Inspector as well as your other scripts. That cross-script access is often unnecessary, especially in simple games. [SerializeField] gives your Inspector access while keeping the variable inaccessible for your other scripts.

You could make everything public, but all the added access can leave your code prone to extra errors. Also, it might bog down game performance as well because your script will be keeping an eye out for calls from other scripts, but I am not 100% sure.

1 Like

I think a philosophy of OOP is that you shouldn’t be directly accessing the variables of other classes. It’s more common to be using getters and setters as opposed to directly accessing those variables. The methods that are public and alter those variables are kind of like the functionality of that object that is provided to the user. But the actual variables themselves are kind of like the inner workings of the class that should be hidden from the user. So serializefield gives us a way to have a variable on the inspector without allowing other classes to directly access that variable which is more in line with OOP philosophy. I don’t know exactly why it’s like this though.

1 Like

Hi Nina,
I’m aware that other links exist but I’m unsure if replying them is a suitable thing to do. Refer to :


Since we used this in the tutorial, I prefer this website to the unity forum. I’m not interested in another nasty reply which spoils my mood and make me fed up. I have this to say:
Since as programmers, only programmers / game designers can see the properties of the serializefield, I suppose it’s only for troubleshooting and design purpose. The point is we don’t see this when we load the game in our devices, whether it is a mobile or desktop / laptop. Let me know if I’m wrong.

Hi,

You are right. The [SerializeField] attribute is meant for us game developers to make our lives easier. It does not appear in the final build, just in the Inspector in Unity. :slight_smile:

1 Like

Privacy & Terms