Hello everyone! So generally I've got some understanding of writing scripts and implementing some mechanics to my game projects. However, one thing I've never really understood properly is when and why I should use public/protected/private etc. for variables and methods. Most of the time, I try to keep everything as private as possible, to the point where I even duplicate logic between scripts just to avoid referencing variables from outside.** I only reuse logic** if I can pass variables to a method within the same script. That way, I don’t have to make anything public or protected between scripts.
But here is the thing I've always wondered:
- How does this impact RAM/ROM usage while running a game?
- Does code privacy actually change after obfuscation?
- Can hackers access variables/methods if they’re marked public, more easily?
- I’ve also seen people use public void Start() and others use private void Start() or even protected override void Start(). What’s the point of changing access levels for Unity in-build methods like Start()?
To give you a better idea of what I mean, I’ve attached a screenshot of a ThrowGrenade() method from my game. Right now, I duplicate the same logic for each type of grenade, instead of making one reusable function and passing specific variables like:
- The current grenade prefab
- The grenade’s script component
I think that this could be handled with cleaner code and proper use of access modifiers, inheritance, etc. , but I'm unsure how to structure it without sacrificing privacy or breaking variables' flexibility between different scripts.
So my final question is: How do I decide which access level like: public/protected/private & internal/abstract/override/virtual to use for my variables and methods?