Declaring Public and Private in Unity

I don’t really get what these two mean. When they say public can be changed by other people, do they mean they change through the inspector or in game like stat buffs?

31st Dec 2019, 7:47 AM
2 Answers
+ 4
When they say it can be changed by other people, they mean any other script can modify the variable without your control. One downside is that this can in theory cause huge headaches if you're working in a team. And even alone, can make you re-write extra code. Say for example we have hp. public int hp or private int hp; If it were public: player.hp -= 10; // Take dmg if (player.hp <= 0) // Die check player.die (); If it were private: player.takeDmg (-10); // Reduce hp by 10 The setter for hp will already assure the player does not survive when hp is less than 0. So, private variables help enforce a rule. Whenever hp is reduced you MUST check if it goes negative. With a public variable, this is not necessarily the case. Some recommend to always keep all variables private. Then, when you need more than that, put them to protected. Then public. I like and follow this ideologically too. You can use: [SerializeField] private int hp; To allow the private variable to be shown in the inspector window.
2nd Feb 2020, 9:33 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
If your variable is public you can change its value from inspector tab in unity but which variable you have define private you cannot access those variable from unity inspector.w e mainly define private and public variable when we are coding in unity for our game just for testing purpose.
31st Dec 2019, 9:16 AM
Maninder $ingh
Maninder $ingh - avatar