What are Namespaces for?

I was wondering why you would use namespaces for scripting, instead of GetComponent or Static variables? I have seen many people use namespaces, but I never new what the point of them was. If anyone could explain in detail, that would be very appreciated!

What is google for?

Namespaces have nothing to do with static variables or GetComponent (except that you might have to qualify the type elsewhere in your code).

It’s an organizational construct that allows you to group your code into “categories”. From a Unity perspective, if you hit the Add Component button in the Inspector and select Scripts then the sub-menu that appears will use your namespaces to break out your classes into sub-sub-menus.

Beyond that, this is more of a C# language question and not necessarily a Unity-specific one. I’d suggest reading some C# literature or checking out the namespace articles on MSDN.

Looking stuff up :wink:

Imagine we have a button. It makes sense to make a class called “Button” right? The problem with this is that a button is a really common thing, so a lot of packages want to have a class called “Button”

This was solved in the past by having a lot of classes that are similar, but not quite, “Button”.

  • NGUI has something called a UIButton.
  • EZGUI might have something called an EZButton.
  • My game might have something called MyGameButton.

Namespaces lets us just call stuff “Button” and tell the compiler which kind of Button we are talking about. So instead of three classes above, we might have NGUI.Button, EZGUI.Button, and MyGame.Button. We can refer to the Button class with those names, or put “using MyGame;” at the top of a script and the compiler knows whenever I write “Button” I mean “MyGame.Button”.

Then I don’t have to come up with ridiculous class names when all I want to do is implement a button.

To extend Garth’s answer, they help avoid name clashes. Lets say I’m making a game and I have a class called Button, and I import a package where someone else already has a thing called Button. How can the compiler tell which button any of the code is talking about? This causes errors because the compiler can’t tell which one of the two Buttons any piece of code is talking about unless there’s some extra information to differentiate the two.

A namespace is that information. By keeping our code in namespaces we don’t need to worry about it clashing with other code that we might bring into our project, because the extra information stops things from being ambiguous.