Organising your Codebase with Namespaces!

This is just a quick article on how we can use namespaces to organise our codebase, namely by keeping groups of scripts separated from each other.

I previously needed to use these when merging multiple Unity projects into one, creating a number of conflicts in the process. For instance, both games had their own ‘Player’ class and their own ‘GameLogic’ (manager) class, and since both of these classes didn’t exist within a specific namespaces the compiler gets confused over which of these instances you’re referring to.

Creating your own namespace is as easy as nesting your classes within a ‘namespace [namespace name]’ statement:

In the above example, I can have two ‘Player’ classes in separate namespaces. In order to access one of these from another class you can do either of two things:

1) You can specify which class you’re referring to by prefixing the reference with a namespace and dot operator (e.g. ‘Game2.Player’).

This can be particularly handy in those instances when a class actually needs to know about and access both Player classes (which I’ve had to do with menu scripts which allow you to access either game).

The main drawback of this approach is that it can feel a little clunky, and might require you to edit a lot of your code just to specify which Player class you’re using.

2) You can place your other classes inside the same namespace in order for the compiler to know which class instance you’re referring to.

For instance, let’s say a GameLogic script needs to reference and use an instance of the Game2 namespace’s Player class. We can in fact just nest this GameLogic class inside the same namespaces, and the compiler will automatically know which Player class we’re referring to:

What’s more, let’s say we have a FeedbackController and a PersistentData class for both games — we could sort these into their respective namespaces (either Game1 or Game2) and then whenever the FeedbackController needs to speak to its game’s Player, GameLogic, or PersistentData class, it’ll know exactly which classes to refer to.

As a quick note, we can also add namespaces or refer to a specific class within a namespace at the header of our scripts:

This can all be very handy for keeping things a little more manageable in particularly large projects 😉

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store