You've successfully subscribed to Hacking with Unity - Learn how to create your own games
Great! Next, complete checkout for full access to Hacking with Unity - Learn how to create your own games
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Namespaces in C#

Ben Liu
Ben Liu

Namespaces are like containers for classes, which can help us organize the code, we see the same concept in other programming languages such as Java, Python and other languages. The purpose of Namespace is to avoid variable or class conflicts and ambiguity. For example both of UnityEngine and System have the class name called Random. So we have to specify which namespace we are using.

create a namespace

Here is one example of creating namespace in csharp.

using UnityEngine;
using System.Collections;

namespace SampleNamespace {
  public class SomeClass: MonoBehaviour {
    void Start() {
      // some code here
    }
  }
}

Use a namespace

There are 3 ways of using a namespace:

// Method 1:
// import the namespace name on the top
using SampleNamespace;

// Method 2:
// use the dot to refer a class name from a namespace
SampleNamespace.SomeClass myClass = new SampleNamespace.SomeClass();

// Method 3:
// similar to create a class
namespace SampleNamespace {
  public class SomeClass2: MonoBehaviour {
    void Start() {
      SomeClass myClass = new SomeClass();
    }
  }

}

Ben Liu

Please feel free to contact me if you have any question. <br> https://t.me/NeedoneApp