[Unity] Instantiate() 활용 예제

Southbig·2023년 3월 9일
0

반복문에 따른 오브젝트 생성

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

public class ObjectSpawner : MonoBehaviour
{
    [SerializeField]
    private GameObject boxPrefab;

    private void Awake()
    {
        for(int i = 0; i < 10; ++ i)
        {
            Vector3 position = new Vector3(-4.5f + i, 0, 0);
            Quaternion rotation = Quaternion.Euler(0, 0, i * 10);

            Instantiate(boxPrefab, position, rotation);
        }
    }
}

중첩 이중반복문에 따른 격자형식 생성

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

public class ObjectSpawner : MonoBehaviour
{
    [SerializeField]
    private GameObject boxPrefab;

    private void Awake()
    {
        // 외부 반복문 (격자의 y축 계산용으로 활용됨)
        for(int y = 0; y < 10; ++ y)
        {
            // 내부 반복문 (격자의 x축 계산용으로 활용됨)
            for(int x = 0; x < 10; ++ x)
            {

                Vector3 position = new Vector3(-4.5f + x, 4.5f - y, 0);
                Instantiate(boxPrefab, position, Quaternion.identity);
            
            }
        }
    }
}

떨어지는 공간이 안나와서 object의 scale를 줄여 주었다

Object Scale 축소

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

public class ObjectSpawner : MonoBehaviour
{
    [SerializeField]
    private GameObject boxPrefab;

    private void Awake()
    {
        // 외부 반복문 (격자의 y축 계산용으로 활용됨)
        for(int y = 0; y < 10; ++ y)
        {
            // 내부 반복문 (격자의 x축 계산용으로 활용됨)
            for(int x = 0; x < 10; ++ x)
            {

                Vector3 position = new Vector3(-4.5f + x, 4.5f - y, 0);
                GameObject newObject = Instantiate(boxPrefab, position, Quaternion.identity); 
                newObject.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f); // change its local scale in x y z format
            }
        }
    }
}

조건문을 사용해 특정 오브젝트 핸들링

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

public class ObjectSpawner : MonoBehaviour
{
    [SerializeField]
    private GameObject boxPrefab;

    private void Awake()
    {
        // 외부 반복문 (격자의 y축 계산용으로 활용됨)
        for(int y = 0; y < 10; ++ y)
        {
            // 내부 반복문 (격자의 x축 계산용으로 활용됨)
            for(int x = 0; x < 10; ++ x)
            {
                if(x == y)
                {
                    continue;
                }
                Vector3 position = new Vector3(-4.5f + x, 4.5f - y, 0);
                Instantiate(boxPrefab, position, Quaternion.identity);
            }
        }
    }
}

임의의 Prefab 생성

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

public class ObjectSpawner : MonoBehaviour
{
    [SerializeField]
    private GameObject[] prefabArray;

    private void Awake()
    {
        for(int i = 0; i < 10; ++ i)
        {
            int index = Random.Range(0, prefabArray.Length);
            Vector3 position = new Vector3(-4.5f + i, 0, 0);
            Instantiate(prefabArray[index], position, Quaternion.identity);
        }
    }
}

Random.Range()

Random.Range() 함수 사용으로 오브젝트 생성시 x,y의 위치를 임의 설정하여 배치

Random.Range(시작, 끝)
파라미터로 시작과 끝의 숫자에서 랜덤의 숫자를 표기

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

public class ObjectSpawner : MonoBehaviour
{
    [SerializeField]
    private int objectSpawnCount = 30;
    [SerializeField]
    private GameObject[] prefabArray;

    private void Awake()
    {
        for(int i = 0; i < objectSpawnCount; ++ i)
        {
            int index = Random.Range(0, prefabArray.Length);

            float x = Random.Range(-7.5f, 7.5f); // x 위치
            float y = Random.Range(-4.5f, 4.5f); // y 위치
            Vector3 position = new Vector3(x, y, 0);
            Instantiate(prefabArray[index], position, Quaternion.identity);
        }
    }
}

spawn point

  1. object로 spawn 위치를 정하고
  2. 하기의 코드 적용후
  3. 코드로 만들어 놓은 spawn point Array의 Element에 object를 추가하면
  4. 추가 된 object에서 임의의 object들이 생성이 된다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectSpawner : MonoBehaviour
{
    [SerializeField]
    private int objectSpawnCount = 30;
    [SerializeField]
    private GameObject[] prefabArray;
    [SerializeField]
    private Transform[] spawnPointArray;

    private void Awake()
    {
        for(int i = 0; i < objectSpawnCount; ++ i)
        {
            
            int prefabIndex = Random.Range(0, prefabArray.Length);
            int spawnIndex = Random.Range(0, spawnPointArray.Length);

            Vector3 position = spawnPointArray[spawnIndex].position;
            GameObject clone = Instantiate(prefabArray[prefabIndex], position, Quaternion.identity);
            // Instantiate(prefabArray[index], position, Quaternion.identity);
        }
    }
}

Move

생성된 오브젝트 움직임

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

public class ObjectSpawner : MonoBehaviour
{
    [SerializeField]
    private int objectSpawnCount = 30;
    [SerializeField]
    private GameObject[] prefabArray;
    [SerializeField]
    private Transform[] spawnPointArray;

    private void Awake()
    {
        for(int i = 0; i < objectSpawnCount; ++ i)
        {
            
            int prefabIndex = Random.Range(0, prefabArray.Length);
            int spawnIndex = Random.Range(0, spawnPointArray.Length);

            Vector3 position = spawnPointArray[spawnIndex].position;
            GameObject clone = Instantiate(prefabArray[prefabIndex], position, Quaternion.identity);

            // spawnIndex가 0인 오브젝트가 왼쪽에 있기 때문에 오른쪽으로 이동
            // spawnIndex가 1인 오브젝트가 오른쪽에 있기 때문에 왼쪽으로 이동

            Vector3 moveDirection = (spawnIndex == 0 ? Vector3.right : Vector3.left);
            clone.GetComponent<Movement2D>().Setup(moveDirection);            
        }
    }
}

각각의 오브젝트 생성 시점 변경

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

public class ObjectSpawner : MonoBehaviour
{
    [SerializeField]
    private int objectSpawnCount = 30;
    [SerializeField]
    private GameObject[] prefabArray;
    [SerializeField]
    private Transform[] spawnPointArray;
    private int currentObjectCount = 0;  // 현재까지 생성된 오브젝트 개수
    private float objectSpawnTime = 0.0f;

    private void Update()
    {
        // objectSpawnCount 개수만큼만 생성하고 더이상 생성하지 않도록 하기 위해 설정
        if(currentObjectCount + 1 > objectSpawnCount)
        {
            return;
        }

        // 원하는 시간마다 오브젝트를 생성하기 위한 시간 변수 연산
        objectSpawnTime += Time.deltaTime;

        // 0.5초에 한번씩 실행
        if(objectSpawnTime >= 0.5f)
        {
            int prefabIndex = Random.Range(0, prefabArray.Length);
            int spawnIndex = Random.Range(0, spawnPointArray.Length);

            Vector3 position = spawnPointArray[spawnIndex].position;
            GameObject clone = Instantiate(prefabArray[prefabIndex], position, Quaternion.identity);

            // spawnIndex가 0인 오브젝트가 왼쪽에 있기 때문에 오른쪽으로 이동
            // spawnIndex가 1인 오브젝트가 오른쪽에 있기 때문에 왼쪽으로 이동
            Vector3 moveDirection = (spawnIndex == 0 ? Vector3.right : Vector3.left);
            clone.GetComponent<Movement2D>().Setup(moveDirection);

            currentObjectCount ++;   // 현재 생성된 오브젝트의 개수를 1 증가시킨다
            objectSpawnTime = 0.0f; // 시간을 0으로 초기화 해야 다시 0.5초를 계산할 수 있다
        }
    }
}

플레이어 위치에서 오브젝트 생성

플레이어가 될 게임오브젝트를 하나 생성하고, 생성된 오브젝트인 플레이어의 위치에서 특정키를 입력시 오브젝트가 생성되도록 만들어 본다

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

public class PlayerController : MonoBehaviour
{
    [SerializeField]
    private KeyCode keyCodeFire = KeyCode.Space;
    [SerializeField]
    private GameObject bulletPrefab;
    private float moveSpeed = 5.0f;

    void Update()
    {
        // 플레이어 오브젝트 이동
        float x = Input.GetAxisRaw("Horizontal");
        float y = Input.GetAxisRaw("Vertical");

        transform.position += new Vector3(x, y, 0) * moveSpeed * Time.deltaTime;

        // 플레이어 오브젝트에서 오브젝트 생성
        if(Input.GetKeyDown(keyCodeFire))
        {
            GameObject clone = Instantiate(bulletPrefab, transform.position, Quaternion.identity);

            clone.name = "Bullet";
            clone.transform.localScale = Vector3.one * 0.5f;
            clone.GetComponent<SpriteRenderer>().color = Color.red;

        }
    }
}

생성된 오브젝트 플레이어 방향에 맞추어 이동

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

public class PlayerController : MonoBehaviour
{
    [SerializeField]
    private KeyCode keyCodeFire = KeyCode.Space;
    [SerializeField]
    private GameObject bulletPrefab;
    private float moveSpeed = 5.0f;
    private Vector3 lastMoveDirection = Vector3.right;

    void Update()
    {
        // 플레이어 오브젝트 이동
        float x = Input.GetAxisRaw("Horizontal");
        float y = Input.GetAxisRaw("Vertical");

        transform.position += new Vector3(x, y, 0) * moveSpeed * Time.deltaTime;

        // 마지막에 입력된 방향키의 방향을 총알의 발사 방향으로 활용
        if(x !=0 || y != 0)
        {
            lastMoveDirection = new Vector3(x, y, 0);
        }

        Debug.Log(keyCodeFire);

        // 플레이어 오브젝트 총알 발사
        if(Input.GetKeyDown(keyCodeFire))
        {
            GameObject clone = Instantiate(bulletPrefab, transform.position, Quaternion.identity);

            clone.name = "Bullet";
            clone.transform.localScale = Vector3.one * 0.5f;
            clone.GetComponent<SpriteRenderer>().color = Color.red;

            // 생성된 오브젝트 방향 적용
            clone.GetComponent<Movement2D>().Setup(lastMoveDirection);
        }
    }
}
profile
즐겁게 살자

0개의 댓글