낑깡의 게임 프로그래밍 도전기

C# Unity Instantiate에 대한 상세 요약 정리 본문

Unity C#

C# Unity Instantiate에 대한 상세 요약 정리

낑깡겜플밍 2023. 8. 25. 20:42
반응형

1. Instantiate 개요

Instantiate는 Unity에서 오브젝트를 복제(인스턴스화)하는 함수로, 주로 프리팹이나 씬 내의 기존 게임 오브젝트를 복제하는 데 사용됩니다.

오브젝트 복사하는법

벡터로 하면 월드기준

TRANSFORM은 월드기준

public static Object Instantiate(Object original);
public static Object Instantiate(Object original, Transform parent);
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);

2. 기본 사용법

2.1 가장 기본적인 오브젝트 생성

GameObject clone = Instantiate(prefab);
  • prefab: 복제할 게임 오브젝트 또는 프리팹
  • clone: 생성된 게임 오브젝트

2.2 위치와 회전 지정하여 생성

GameObject clone = Instantiate(prefab, new Vector3(0, 1, 0), Quaternion.identity);
  • new Vector3(0, 1, 0): (x=0, y=1, z=0) 위치
  • Quaternion.identity: 회전 없음

2.3 부모(Parent) 설정

GameObject clone = Instantiate(prefab, parentTransform);
  • parentTransform: 생성된 오브젝트가 속할 부모 오브젝트

2.4 위치, 회전 및 부모 설정

GameObject clone = Instantiate(prefab, new Vector3(0, 1, 0), Quaternion.identity, parentTransform);
  • 부모 설정과 함께 위치와 회전도 지정 가능

 

3. Instantiate 반환 타입

Instantiate는 기본적으로 Object 타입을 반환하므로, 특정 컴포넌트로 캐스팅해야 합니다.

3.1 GameObject로 캐스팅

GameObject clone = Instantiate(prefab) as GameObject;

3 .2 특정 컴포넌트로 캐스팅

Rigidbody cloneRb = Instantiate(prefab).GetComponent<Rigidbody>();

 

4. 성능 최적화

4.1 Instantiate는 동적 할당

  • Instantiate는 새로운 객체를 힙(Heap)에 할당하여 메모리를 사용하므로, 너무 자주 사용하면 GC(가비지 컬렉션) 로 인해 성능 저하가 발생할 수 있음.
  • 해결 방법: 오브젝트 풀링(Object Pooling) 사용.

4.2 Instantiate 후 최적화

  • 생성 후 필요한 초기화 과정을 거쳐야 메모리 낭비 방지.
GameObject clone = Instantiate(prefab);
clone.transform.position = new Vector3(0, 1, 0);
clone.transform.rotation = Quaternion.identity;

5. Instantiate 응용

5.1 부모 없이 생성 후 부모 설정

GameObject clone = Instantiate(prefab);
clone.transform.SetParent(parentTransform, false);
  • false: 로컬 위치 유지

5.2 프리팹을 여러 개 생성

for (int i = 0; i < 5; i++)
{
    Instantiate(prefab, new Vector3(i * 2, 0, 0), Quaternion.identity);
}
  • 2 유닛 간격으로 5개 생성

5.3 Instantiate 후 변수 초기화

Enemy enemy = Instantiate(enemyPrefab, transform.position, Quaternion.identity).GetComponent<Enemy>();
enemy.SetHealth(100);
  • GetComponent<T>()를 사용해 필요한 컴포넌트 접근 후 초기화

 

6. 주의사항

6.1 Instantiate는 프리팹이 반드시 존재해야 함

if (prefab != null)
{
    Instantiate(prefab);
}
  • null 체크 필수

6.2 Instantiate 후 반환값을 활용하지 않으면 메모리 낭비

Instantiate(prefab); // 생성만 하고 변수에 할당하지 않으면 추적 어려움
  • 가능하면 생성 후 변수에 저장하여 관리

6.3 Instantiate한 오브젝트는 직접 Destroy() 해야 함

GameObject clone = Instantiate(prefab);
Destroy(clone, 3f); // 3초 후 삭제

7. 요약 정리

  Instantiate는 오브젝트를 복제하는 함수
  위치, 회전, 부모를 설정 가능
  Instantiate 후 반환된 오브젝트를 변수에 저장하여 관리
  너무 자주 사용하면 성능 저하 가능 → 오브젝트 풀링 고려
  Destroy()를 활용하여 불필요한 오브젝트 정리

반응형