유니티 개발을 하다보면 간혹 컴포넌트와 gameObject를 혼동할 수 있다.
GameObject와 Component의 관계를 이해하는 것은 매우 중요한데, 간단히 정리하면 GameObject는 Component객체를 담는 컨테이너(Container)다. Component는 자신이 포함된 GameObject 객체에 대한 참조를 가지고 있어야한다.
따라서 destroy(this)를하면 해당 인스턴스 즉 컴포넌트만 삭제가 되고 gameObject는 삭제가 되지 않는다. 하지만 destroy(gameObject)를 하면 해당 gameObject객체와 그 오브젝트에 딸린 컴포넌트 모두 제거가 된다.
예시로 다음과같은 코드가 있다.
public class TerritoryManagement : MonoBehaviour
{
[SerializeField] TerritoryManagementExitButton territoryManagementExitButton; //뒤로가기 버튼을 생성한다.
private void Awake()
{
var tmp = Instantiate(territoryManagementExitButton,GameObject.Find("Canvas").transform);
tmp.territoryManagement = this;
}
}
public class TerritoryManagementExitButton: MonoBehaviour
{
public TerritoryManagement territoryManagement { get; set; }
public void OnClick()
{
//영지관리 destroy
Destroy(territoryManagement.gameObject);
}
}
이때 tmp.territoryManagement = this부분에서 tmp.territoryManagement = gameObject를 하면 에러가 발생한다. 컴포넌트와 gameObject는 다르기 때문이다.
또한 Destroy(territoryManagemet)만 하면 인스턴스화 되어 하이어라키 창에 올라와있는 GameObject는 제거되지 않는다. 컴포넌트 제거만 지시하였기 때문이다.
'C#_ Unity Game programming' 카테고리의 다른 글
Unity - 오브젝트 풀링을 써야하는 경우 (1) | 2024.01.30 |
---|---|
Unity - 프리팹 인스턴스화 메모리 개념 및 에셋번들, 어드레서블 에셋 (0) | 2024.01.15 |
Unity-Instantiate할 때 Canvas의 자식으로 넣는법 (1) | 2024.01.13 |
Unity, UI제작시 프리팹 및 풀링 고려(가비지 문제) (0) | 2024.01.12 |
유니티 C#, 인터페이스를 활용한 성능 향상 실습 (0) | 2024.01.06 |