Hello, I have two silly questions.
Is a variable in private really important? except for hiding the variable from the inspector.
A public variable, could be different on each game object or the script of this variable will be attached and modified without creating a problem?
- private means instances, or in a case where a class is static, the calling class, cannot see the variable or function. private is important when you dont want a variable to be changed from another class.
- public means its available to all.
- protected means its only available to derived classes from that base class.
when you create an instance of a class, you’re creating a new object. all the variables in that object are unique to that specific object. public, private and protected does not matter in that case. it wont change the fact that every object is unique.
modifying that variable will only change that variable for whatever object is attached.
1 Like
When you make a variable public you are enabling read/write access on that variable from every other class in your entire codebase.
Let’s say you have a HealthSystem with a public int health; and you find a weird bug where your player’s is changing for some reason. In order to identify that bug you need to look into your entire codebase, which can be just 10 classes or maybe 10,000. Since you made it public then every other class anywhere in your codebase can access and modify that field.
Whereas if you make it private and you limit access as much as possible (perhaps through limited Damage() and Heal() functions) then it makes it much much easier to find that bug since there’s many fewer entry points that can modify that variable.
Your main goal as a programmer is to minimize complexity, you want to keep as few things in your brain at one time as possible, doing so will make continued development, adding features and finding bugs much much easier.
If you want to make something easy to edit in the Editor but still keep your code nice and clean, then the correct way to do it is:
[SerializeField] private health;
That way the variable stays private so only that class can directly access it while also remaining editable in the Editor.
I made a whole video on this topic, writing good clean code is extremely important especially as you make more complex games.
1 Like
I thank you both.
It’s easier for me now.
I better understand the interest of [SerializeField], I asked myself the question.
I had already seen your CodeMonkeyYT video, I appreciate your content.
I still have a little trouble understanding everything about unity, a lot of information to integrate, but little by little we are moving forward ^^
Thank you again 