@Rob is right with the best practice. To try to help you understand why, let’s look at an example.
Let’s say I have a class ScoreManager
which takes care of all scoring functions in my game.
If it has a public field score
, any code anywhere in the game can update the score by getting a reference to the active ScoreManager and calling ScoreManager.score =
(there’s some subtlety here with instance names but you get the idea).
This is generally undesirable, because there are other things the ScoreManager might want to do when adjusting the score - logging, firing Events, firing Analytics, etc. You want to control access to the score
field to force it to update the way you want to.
So you make it private, which locks score
down to only the ScoreManager
class. You might provide methods such as public void IncrementScore(int)
to allow other classes to suggest a score update (rather than changing the score directly) and you then have control in IncrementScore
over how the ScoreManager chooses to do that.
Of course if another class just wants to know the score but not change it, you’ll need to provide a method public int GetCurrentScore()
or similar. Another way to do this is to declare the score as follows:
public int score {get; private set;}
This allows any class to read the score, but only the enclosing class to change it. I mostly use this form in my code for fields unless I need to make them public to expose them to the editor.
Hope this helps