C# 유니티 - 인스턴스화

Se0ng_1l·2022년 7월 25일
0
post-thumbnail

이 글은
https://www.inflearn.com/course/유니티-게임-프로그래밍-에센스
강의를 요약한 강의노트 입니다.
유니티를 처음 접하시는 분들이거나 좀 더 기반을 다지고 싶으신 분들에게 👍강력하게 추천합니다.

📌인스턴스화

인스턴스화란, 어떤 대상을 실존하는 무언가로 찍어내는 것을 말한다.
유니티에서 인스턴스화는 게임 도중에 만들어 놓은 오브젝트를 생성하는 것을 말한다.
ex) 총알, 몬스터...

선언

public GameObject target;
void Start()
{
    Instantiate(target);
}

target의 오브젝트로 들어갈 오브젝트는 주로 프리펩을 통해 오브젝트를 만들어낸다.

인스턴스에 여러가지 옵션도 부여할 수 있다.

위치, 회전

public GameObject target;
void Start()
{
    GameObject instance = Instantiate(target, spawnPosition.position, spawnPosition.rotation);
}

리지드바디

1️⃣

public GameObject target;
public Transform spawnPosition;

void Start()
{
    GameObject instance = Instantiate(target, spawnPosition.position, spawnPosition.rotation);
    // 인스턴스에 인스턴스화 한 타겟의 오브젝트가 들어온다.
    Debug.Log(instance.name);
    // 인스턴스화한 오브젝트의 이름은 원래이름(clone)다.

    instance.GetComponent<Rigidbody>().AddForce(0, 1000, 0);
}

2️⃣

public Rigidbody target;
public Transform spawnPosition;

void Start()
{
    Rigidbody instance = Instantiate(target, spawnPosition.position, spawnPosition.rotation);
    // 인스턴스에 인스턴스화 한 타겟의 오브젝트가 들어온다.
    Debug.Log(instance.name);
    // 인스턴스화한 오브젝트의 이름은 원래이름(clone)다.
    
    instance.AddForce(0, 1000, 0);
   
}

차이점
1️⃣의 경우 리지드바디를 사용하기 위해 Gameobject로 먼저 인스턴스를 받은 후 다시 Getcomponent리지드바디를 받아와야한다.
2️⃣과 같이 짤 경우 인스턴스의 생성과 동시에 instance에 target의 rigidbody컴포넌트가 할당되어 바로 실행할 수 있다.

profile
치타가 되고 싶은 취준생

0개의 댓글