Namespace in c# and Unity

A namespace is a library of classes and methods that we declare within a project and that we can later recall entirely, only when we really need it.

In programming languages they are called libraries or packages and are declared at the top of the code, there are many of them for different operations, and recalling them all would weigh too much the code. So they are divided into blocks and called only when they are needed.
The same thing happens in Unity.
The UnityEngine namespace contains all the main methods that allow you to use the MonoBehaviour, the definition of additional types such as Transform RigidBody, GameObject, and many others.

To declare a namespace we must use the keyword “namespace” followed by the name we want to give it and insert our classes and methods between the curly brackets.

To call it and use it also in other scripts we just need to use the keyword “using” as for normal libraries.

When should it be used?

  • In a very big project, it can be convenient to have a namespace to call directly a certain type of class.
  • when we import a package of unity with scripts that have classes with the same names as our existing classes. We just need to put our classes in a namespace to solve the problem.
    But remember that then you have to call the namespace otherwise the compiler will take the reference of the other class with the same name.
  • When we work mainly always on a certain type of project, it becomes natural to write classes and methods that are used in multiple projects, and then for convenience, we create a kind of framework with namespaces.

project manager by day, unity developer by night