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?

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 :slight_smile:

Good info here, now that I kinda know what I’m doing, I’m trying to always use the best practices on my code, so I was wondering, which of these two ways is better?

A)
declare public float

Update(){
write/read to float
}

B)
Update(){
declare private float
write/read to float
}

I’d think that it’s better to just declare once as a public than constantly creating/removing from memory but I’m no expert… Thanks a lot for the help