Why not use public variable?

Public variable works perfectly fine for me, and it should even be able to be tweaked by anything in the scene that needs to, so if anything this should work better.

It depends on the circumstances to what’s required.

Public variables work until they get you into a situation where they get you into trouble.

1 Like

even be able to be tweaked by anything in the scene that needs to

Interestingly this is one of the reasons why you shouldn’t always use it.
Many people do though, infact most people I see use public variables instead of SerializeField, recently I did the Unity Begineer course and they’ve only talked about public also.

In any case, the reasoning comes into safety and readability. If I see someone elses code, I should be able to see the variables at the top and know “the ones with public is being used/tweaked elsewhere” and “the ones with SerializeField means likely variables are being updated/changed in the editor” without having to look over ALL your code.

You might also have names that are similar, or code you don’t want tweaked and you want to ensure it won’t be able to, either through other peoples codes, or yourself accidentally. It also helps in debugging your code as well.

2 Likes

Public variable also makes the variable accessible by other scripts which u don’t want in some scenarios
while [SerializeField] keeps the variable Private while making it visible on the Inspector window

You can also hide Public variables from the inspector using [HideInInspector], it’s absolutely fine to never need/use any of these, but the option to do so is there anyway, and that’s what I like about programming, there’s always different ways to achieve the same result

1 Like

Privacy & Terms