본문 바로가기
Unity

[유니티] 지정위치에 랜덤 오브젝트 놓기

by Skull Crusher 2021. 4. 24.
728x90

1. 3D Cube 생성

이름 바꾸기 ->RunScriptGameObject -> 인스펙터에 Mesh Renderer 클릭해제

** 네이밍이 중요하다**

2. C# Script 만들기

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

public class CSharpArray : MonoBehaviour
{
    // 게임오브젝트 배열 참조변수
    public GameObject[] gameObjects;

    // Start is called before the first frame update
    void Start()
    {       
      
    }
    
    // Update is called once per frame
    void Update()
    {
        
    }
}

3. 빈 오브젝트 생성

이름 바꾸기 -> GenPositions

4. GenPositions 클릭하고 다시 빈 오브젝트 5개 생성 (자식으로 들어감)

이름 바꾸기 -> Position1~5 -> 인스펙터에서 색 지정

5. 만들 3D 캐릭터 생성

3D Cube 생성 -> 그림 넣기 -> prefabs 폴더에 드레그 -> Hierarchy 에서는 삭제하기

6. C# Script 생성 

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

public class CubeGenerator : MonoBehaviour
{
    public int[] datas;

    public Transform[] positions;

    // 생성할 오브젝트 선택
    //public GameObject orgePrefab;
    //public GameObject orcPrefab;
    //public GameObject goblinPrefab;

    public GameObject[] monsterPrefabs;

    // Start is called before the first frame update
    void Start()
    {
        // datas = new int[5];

        // 배열변수.Length -> 배열의 갯수

        // 위치 참조 배열을 순차적은 반복하면서
        for (int i = 0; i < positions.Length; i++)
        {
            // 랜덤한 몬스터의 배열번호를 추첨하여
            int monterType = Random.Range(0, monsterPrefabs.Length);

            Instantiate(monsterPrefabs[monterType], positions[i].position, Quaternion.identity);
        }

        //int monsterType = Random.Range(0, 3);

        //if (monsterType == 0)
        //{
        //    Instantiate(orgePrefab);
        //}
        //else if (monsterType == 1)
        //{
        //    Instantiate(orcPrefab);
        //}
        //else if (monsterType == 2)
        //{
        //    Instantiate(orcPrefab);
        //}
    }

    // Update is called once per frame
    void Update()
    {

    }
}

7. GenPositions에 CubeGenerator 스크립트 추가

GenPositions 인스펙터에 Position1~5 연결 -> 만들어 놓은 prefabs 연결

8. 완성모습!!

'Unity' 카테고리의 다른 글

[유니티] 회전하기  (0) 2021.05.14
[유니티] 3D 캐릭터 이동하기  (0) 2021.05.13
[유니티] 효과 넣기  (0) 2021.05.06
[유니티] 3D 점수 계산  (0) 2021.05.06
[유니티] 3D 큐브 생성 + 회전하기  (0) 2021.04.21

댓글