Automatically Adding Namespace in Unity C# script

Prasetio Nugroho
2 min readMay 27, 2022

When your project is getting bigger, somehow you should naming your classes with uniqe name. Sometime, our classess name is the same as plugin classes name, this makes it a little annoying. To solve it, we should rename it. Actually, there is best practice from C# to avoid this problem. We can add namespace in our created script.

A namespace is simply a collection of classes that are referred to using a chosen prefix on the class name — unity documentation

The namespace keyword is used to declare a scope that contains a set of related objects. You can use a namespace to organize code elements and to create globally unique types. — microsoft documentation

Adding namespace manually

Let say, there is a class name with name PlayerController from your plugin.

PlayerController.cs from plugin

Then we can use namespace in our created script, let say our namespace MyPlayer.

adding namespace

Our created script PlayerController.cs does not conflict with PlayerController.cs from plugin. This method still has limitation. When we created script, we should add one by one in our script. What if there are one hundred script, it willl take much effort to do it.

Adding automatically namespace in created script

In unity, we can add configuration to add automatically namespace when we create a new script. You can setup the config in Edit -> Project Settings -> Editor -> C# Project Generation Section, then add your name of namespace in Root Namespace

root namespace setup

After we add name in root namespace, when we create a new script, it will be automatically added.

namespace automatically added

Then if you want use your classes with namespace in another class, you can call the namespace first then classname,

CustomNamespace.PlayerController.SomeMethods();

or you can use “using” followed by your namespace, then call classess with method inside your another classes.

using CustomNamespace;

Conclusion

When your project is getting bigger, you should using namespace. It will help you prevent duplication of your class names in your script.

Reference

--

--

Prasetio Nugroho

Interested in new tech, gaming, programming and another knowledge or possibilites that can make me better. Cheers!!