What are Namespaces?
Namespaces are basically helping you isolate and organize your scripts. You can think of them like folders for scripts, think about it, we somehow need to group scripts together and better understand and link their behavior. Well Namespaces does exactly that!
But you may ask, why do I need to group my scripts in namespaces? I already have my scripts separated in folders to organize them so it wouldn’t make any real difference right?
Well yes and no. On the surface, it really doesn’t make a visual difference to how you structure your code but it helps the engine understand where each script belongs. By separating scripts using Namespaces, the engine understands better which scripts are together and which are not.
This is great because that means that we can have the same Name for 2 different classes if they are in different namespaces. Okay but I can just not use the same class name twice and problem solved right? Yes, that is the case if you work alone and you are in charged of all class names, sure. But when you work with another programmer or with 50 other programmers or when you download an asset pack that has code written, you will sooner or later end up having sae name conflicts.
For example, lets say you are building a First-Person Shooter game and have an enemy class called Enemy where you have all the enemy behavior there. While coding, you face a code-block and cannot understand how to implement the Enemy Shooting mechanic so you do what all game developers do. You take a break and think again You search only for ready-made code to help- you. You come across an asset pack that has this mechanic and instantly download it only to be covered in conflict messages about same Class Names.
By using namespaces you can easily avoid this conflicts and enjoy ready made code!
Best Practises for Namespaces
Using Namespaces is very easy and straight forward as it only requires to add 1 line in our code.
At the top of the script add “namespace NameOfNamespace{}” and add ALL your code inside the brackets. In this example I placed all my code inside a namespace called EJETAGame.
And thats really it, now we have created a namespace where we can place similar scripts inside! Usually I try to create self-explanatory namespaces where the name indicates what type of scripts are placed inside. Some of my namespaces are called:
- Combat
- UI
- NPCs
- Player
- Environement
- Inventory
- Audio
- Abilities
If I ever need a different namespace script to contact another one, I can simply import that namespace using the “Using” keyword at the top of my script like this:
Seems familiar right?
Yes! Unity is of course using namespaces to group all its content, and we see examples of it each time we create a new Monobehaviour script at the top. Now we can use all the scripts said namespace has!