Namespaces are collections of libraries of code that allow extra functionality in your project. Unity comes with three default System.Collections and System.Collections.Generic and then UnityEngine. There are variety of different namespaces provided by Unity such as UnityEngine.SceneManagement which (naturally) controls management of scenes. Another helpful and common namespace is UnityEngine.UI which controls UI and Canvas functionality.
Aside from functionality that namespaces add they also serve as organization tools. If you have a collection of helper scripts and methods that deal with AI, naming it GreatAI can help you encapsulate it in a namespace where it’s organized but also figure out how that differs from UnityEngine.AI which may have similar sounding or identical methods and fields. Creating your own namespaces is fairly straight forward let’s take a look below.
So you have your namespace and it’s name followed curly braces to encapsulate the code below it. Then you can fill it with anything you like classes and etc. Those then hold the fields and methods of your namespace. To use it all you have to do is add using and then the namespace at the top of your scripts otherwise you hit errors like this where you can’t find the class you want assuming they’re accessible.
You can prefix the field with Namespace.Variable Type like below and also call it that way but generally using the using statement is ideal and cuts down on clutter.
As you’ve seen namespaces are powerful ways to help organize your code, cut down on conflicts, and encapsulate important data. It also serves to modularize your code as you can bring and snip out namespaces as necessary cutting down on complexity. Until next time, happy coding.