[유니티] Unity Instantiate

안녕하세요 UnityBeginner입니다.
이번 글에선 오브젝트를 복제하는 Instantiate에 대해 알아보겠습니다.

씬뷰

다음 이미지와 같이 복제를 하기위한 4개의 오브젝트를 생성해줍니다.


스크립트 Instantiate


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public GameObject cube, Cylinder, Capsule, Sphere;

    private void Update() {
        if(Input.GetMouseButtonDown(0)) {

            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if(Physics.Raycast(ray, out hit)) {
                DropObject(hit.collider);
            }
        }
    }

    private void DropObject(Collider col) {

        Vector3 vpos = col.transform.position;
        vpos.y -= 1.5f;

        switch (col.name) {
            case "Cube":
                Instantiate(cube, vpos, Quaternion.identity);
                break;
            case "Cylinder":
                Instantiate(Cylinder, vpos, Quaternion.identity);
                break;
            case "Capsule":
                Instantiate(Capsule, vpos, Quaternion.identity);
                break;
            case "Sphere":
                Instantiate(Sphere, vpos, Quaternion.identity);
                break;
        }
    }

마우스로 클릭시 Raycast를 통하여 클릭지점의 충돌체를 감지하고 
객체의 이름으로 해당하는 오브젝트를 복제하는 코드입니다.

 Instantitate는 다음과 같은 파라미터를 받습니다.
 Instantitate(오브젝트명)
 Instantitate(오브젝트명, 오브젝트위치, 오브젝트회전)
 Instantitate(오브젝트명, 부모객체Transform)



결과화면



기존에 오브젝트를 prefab으로 만들고 instantiate를 통하여 오브젝트 
복제가 가능하며 해당 기능은 각종 게임에서 다양한 방식으로 구현되고있습니다.
(슈팅게임 비행기의 발사되는 총알, 디펜스게임의 적 웨이브 등등)


댓글