Clean code vs the singleton for mouse position

I definitely agree with the point you made about public vs private variables: default should be private, only make it public when it really makes sense.

But, I can’t stop but feel the same way about static/global variables/singletones. You created one here (as in: two lectures back, for mouse position) just to be able to set a variable in the inspector. There was no other need for making it either a singleton, nor a MonoBehavior.

I feel that code cleanliness has a lot to do with what other people reading the code would expect and what makes the reading easier. If I were to see your mouse handling code without any commentary (or indeed, comments) it would definitely take me some time to figure out why you put the singleton in there and if you didn’t have some reasons other than just having access to the layer mask variable. It still does not feel like the right tool for the job to me (unless this is a common pattern among within developers using Unity - I do admit to not having much collaboration experience there).

Aren’t there any cleaner ways to do it? Right now I would lean towards just making a static variable within the class that holds the layer mask (and make the class static as well) - if you ever changed the “Mouse Plane” layer you would probably anyway need to manually update everything in the Inspector, so doing it in code might be actually easier.

Yes statics/singletons should be used sparingly since they’re easy to abuse, but that doesn’t mean you avoid them altogether.
The reason to make it a MonoBehaviour is to easily assign the LayerMask and allow for easy debugging by adding a visual like I showed in that lecture.
Yes you could absolutely not use MonoBehaviour at all, you could hardcode the Layer number and make it static. That is a valid approach but I find having the object on the scene to be easier to manage.

3 Likes

Privacy & Terms