Day 11 | Understanding “Public” vs “Private”
July 17, 2022
Today I’m trying to dive deeper into the idea of “public” and “private” variables. This video called “Why you should NOT make everything PUBLIC!” really helped: https://youtu.be/pD27YuJG3L8
In this video, he talks a lot about keeping your code clean. I think that that’s a really interesting concept. Technically, you can always use public variables, but it will make your code less clean because it will make that variable potentially accessible to other parts of your script or different scripts altogether, when there’s really no need for all of that confusion. It can lead to breaking your game, and then having to spend a lot of time trying to figure out which public variable is accidentally being manipulated.
He suggests using private variables almost always unless absolutely necessary because it leads to less headaches and bugs. When a variable is set to private, it can only be accessed within the class that it was created. However, one downside is that you can’t see the variable within Unity’s editor for easy manipulation. But there’s still a way to have it be private and in the editor as well. That is with the attribute [SerializeField] placed at the beginning of the declared variable.