목표

  • Instantiate를 이용하여, Prefabs를 복제해 본다.
  • 이전 Prefabs를 참고하여 나무를 생성해보자.

Instantiate

  • Instantiate는 런타임에 게임 오브젝트를 복제하는 함수이다.
  • 아래 스크립트를 실행하면, 스페이스가 눌린 경우 나무를 생성되게 된다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TreeGenerator : MonoBehaviour {

    public GameObject TreePrefabs;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Instantiate(TreePrefabs);
        }
    }
}
  • 랜덤한 위치에 나무를 생성하기 위해 Random 함수를 사용했다.
  • 물체의 회전 값은 쿼터니언(Quaternion)을 사용하여 표시하였다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TreeGenerator : MonoBehaviour {

    public GameObject TreePrefabs;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            float posX = Random.Range(-30, 30);
            float posZ = Random.Range(-30, 30);
            Instantiate(TreePrefabs, new Vector3(posX, 0, posZ), Quaternion.identity);
        }
    }
}

  • 복제된 나무의 이름에는 (Clone)이 붙어있다.
  • name을 지정해 주고 싶다면, Instantiate의 리턴값을 참조하여 변경할 수 있다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TreeGenerator : MonoBehaviour {

    public GameObject TreePrefabs;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            float posX = Random.Range(-30, 30);
            float posZ = Random.Range(-30, 30);
            GameObject tree = Instantiate(TreePrefabs, new Vector3(posX, 0, posZ), Quaternion.identity);
            tree.name = "Apple Tree"; 
        }
    }
}

+ Recent posts