대형 프로젝트로 더 많은 스크립트를 사용할수록 스크립트 클래스 이름이 서로 충돌할 가능성도 커집니다. 여러 프로그래머가 게임의 서로 다른 파트를 따로 작업하고 나중에 하나의 프로젝트로 통합할 때 이런 현상이 두드러집니다. 예를 들어, 한 프로그래머가 메인 플레이어의 제어 코드를 만드는 동안 다른 프로그래머가 적 캐릭터에 동일한 코드를 작성하는 경우가 발생할 수 있습니다. 그리고 둘 다 메인 스크립트 클래스에 Controller 라는 이름을 붙이면 프로젝트를 통합할 때 충돌이 일어납니다.
네이밍 규칙을 도입하거나 충돌이 발견될 때마다 이름을 변경하는 식으로 문제를 어느 정도 피해갈 수 있습니다(위의 예에서 PlayerController 및 EnemyController 라는 이름을 붙이기). 그러나 이름이 충돌하는 클래스가 여러 개이거나 해당 이름으로 변수가 선언되어 있다면 번거로운 작업이 될 수 있습니다. 코드를 컴파일하려면 기존 클래스 이름을 각각 대체해야 합니다.
C# 언어는 namespaces 기능으로 이 문제를 확고하게 해결합니다. 네임스페이스는 클래스 이름에 선택한 접두사를 사용하여 참조하는 클래스의 모음입니다. 자세한 내용은 네임스페이스에 대한 Microsoft 문서를 참조하십시오.
아래 예제에서 Controller1 과 Controller2 는 Enemy 라는 네임스페이스의 멤버입니다.
namespace Enemy {
public class Controller1 : MonoBehaviour {
...
}
public class Controller2 : MonoBehaviour {
...
}
}
코드에서 이런 클래스는 각각 Enemy.Controller1
과 Enemy.Controller2
로 지칭합니다. 네임스페이스의 선언이 기존 클래스의 선언 앞뒤에 괄호를 붙일 수 있는 한 클래스 이름을 변경하는 것보다 좋은 방법입니다(즉, 클래스 이름을 전부 일일이 변경할 필요가 없습니다). 또한 클래스가 다른 소스 파일에 있더라도 클래스 앞뒤로 여러 괄호를 친 네임스페이스 섹션을 사용할 수 있습니다.
파일 앞머리에 using을 덧붙여 네임스페이스 접두사를 반복적으로 입력하는 것을 방지할 수 있습니다.
using Enemy;
위의 행은 Controller1 과 Controller2 를 어디에서 찾을 수 있는지 표시하며 각각 Enemy.Controller1 과 Enemy.Controller2 를 의미합니다. 만약 스크립트가 다른 네임스페이스로부터 같은 이름의 클래스를 참조해야 한다면(예를 들어 Player) 접두사도 활용될 수 있습니다. 충돌하는 클래스 이름을 포함하는 두 개의 네임스페이스를 using 지시자로 동시에 임포트하면 컴파일러는 오류를 보고합니다.
Note: Unity has a specific limitation relating to namespaces and MonoBehaviour or ScriptableObject classes. If your file contains a definition for a MonoBehaviour or ScriptableObject class, you cannot use multiple namespaces within that file.
Unity gives the following warning in the console:
Class MyClass can not exist in multiple namespaces in the same file, even if one is excluded with preprocessor directives. Please move these to separate files if this is the case.
This means if you have a file which defines a MonoBehaviour in one namespace, and other classes in a different namespace within the same file, Unity will not recognize the MonoBehaviour class and you will not be able to use it on GameObjects. This limitation was introduced in Unity 2020.1 to improve import and compilation speed, and therefore some older asset store packages written before this limitation was introduced may function incorrectly as a result. To fix problems relating to this issue, separate out the code for the classes in each namespace to separate files.