performance question about public variables vs. private variables
simply put, I have many scripts with public variables...bools and ints and floats, that I made public just so I could tweak while testing or see bools turn on and off. Now that I see that the scripts work and I have the public variables set , should i even bother making them private? I know looking at the script in the inspector it would take up less space but as far as performance goes does it matter? I mean is there any more processing power required to graphically have a bool tick box checked or to update the # in the text field for ints and floats? when you are playing an actual build none of this is visible anyway so maybe I just answered my own question?
Answer by TimHeijden · Apr 23, 2017 at 10:15 PM
As far as I know, the only difference in performance is that any serialized variable (public or with [SerializeField] attribute) is loading the scene. This is because the scene file will be bigger. That said, this is generally a very minor difference unless you have a VERY large amount of them. You can try this out of course, make a script and put it on 1000 objects and you'll see the difference.
The most important reason for public vs. private is Encapsulation. You don't want to have anything public unless you really need them to be. I'd say the best is to:
Use [SerializeField] private bool someValue; For exposing variables to the editor.
Use public only if you need to access the variable from another class / script.
Use private in all other cases.
Encapsulation is important because it makes your code much easier to understand, both for other and yourself when you get back to it later. It also makes your autocomplete much cleaner when you reference other scripts :)
Your answer
Follow this Question
Related Questions
Quick Question on how to write a player class 1 Answer
public vs private array in classes 0 Answers
public and private problem 2 Answers
My C# script crashes Unity and I don't know why, help? 0 Answers
Change public variable with button 1 Answer