목표
- namespace에 대해 알아보자.
와~ 석규옹
namespace
- 스크립트를 제작하면, 대부분 using 지문이 포함되어 있다.
- UnityEngine은 Debug 클래스, System.Collections.Generic은 List나 Dictionary등을 포함한다.
- 이처럼 네임스페이스(namespace)는 개체를 구별하는 범위를 나타낸다.
예제
- 같은 범위(Scope)에 동일한 명칭의 클래스를 생성하게 되면 충돌이 발생한다.
- 2명 이상 혹은 대규모 프로젝트에 참가하다 보면, 종종 내가한 작업과 남이한 작업에 동일한 명칭의 클래스가 생성되는 일이 종종 있다.
- 대부분 Debug거나 Util이거나 하는 이름등이 겹친다.
- namespace를 사용하면 이러한 충돌을 피할 수 있다.
public class Something
{
public static void DoWork()
{
Debug.Log("Something 1 DoWork");
}
}
public class Something
{
public static void DoWork()
{
Debug.Log("Something 2 DoWork");
}
}
소스코드 충돌 회피
- 하지만 namespace로 영역을 나누면 충돌이 없다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Some
{
public class Something
{
public static void DoWork()
{
Debug.Log("Some.Something");
}
}
}
namespace Thing
{
public class Something
{
public static void DoWork()
{
Debug.Log("Thing.Something");
}
}
}
public class SampeScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Some.Something.DoWork();
Thing.Something.DoWork();
}
}
네임스페이스 멤버를 사용한 영역 분할
- namespace에 멤버를 설정하여 영역을 분할할 수 있다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Some.Internal
{
public class Something
{
public static void DoWork()
{
Debug.Log("internal.Something");
}
}
}
namespace Some.Public
{
public class Something
{
public static void DoWork()
{
Debug.Log("public.Something");
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Some.public;
public class SampeScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Something.DoWork(); // "public.Something"
}
}
'프로그래밍 > Unity C#' 카테고리의 다른 글
[Unity] Tutorial 06 - Intermediate Scripting (Coroutines) (0) | 2020.05.27 |
---|---|
[Unity] Tutorial 06 - Intermediate Scripting (Collections) (0) | 2020.05.27 |
[Unity] Tutorial 06 - Intermediate Scripting (Extension Methods) (0) | 2020.05.27 |
[Unity] Tutorial 06 - Intermediate Scripting (Indexer) (0) | 2020.05.21 |
[Unity] Tutorial 06 - Intermediate Scripting (Polymorphism) (0) | 2020.01.20 |