UNITY

[Unity] Instantiate -오브젝트 복제하기

연듀 2021. 10. 12. 16:53

 

 

 Instantiate(복제할 대상, 지정한 위치, 지정한 방향)

 

 

 

Scene에 TowerPos1, TowerPos2라는 빈 오브젝트를 생성한다.

 

 

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class cshMakeTower : MonoBehaviour
{
    public GameObject tower; // 복제할 대상
    public Transform TowerPos1; 
    public Transform TowerPos2;

    public int n = 2;
    // Start is called before the first frame update
    void Start()
    {
        
    }
  
    void Update()
    {
        if(Input.GetMouseButtonDown(0)) // 마우스 왼쪽 버튼 누르면 
        {
           
            if (n == 2)
            {
                Instantiate(tower, TowerPos1.position, TowerPos1.rotation); // 지정한 위치와 지정한 방향으로 tower를 복제하라. 
            }
           

            if (n == 1)
            {
                Instantiate(tower, TowerPos2.position, TowerPos2.rotation);
            }
            n--;

        }
    }
}

 

스크립트를 만들어 Main Camera에 추가해준다.

 

 

 

Tower에 prefab으로 만든 Tower를,

Tower Pos1, Tower Pos2에 빈 오브젝트로 만들어 놓은 TowerPos1, TowerPos2를 드래그한다.

 

실행시켜보면 마우스 왼쪽 버튼을 클릭할 때 지정된 위치로 tower가 복제된다.