etc-posts/Unity :: C# 튜토리얼

[유니티 C#][기초] 3. 씬에 스크립트로 큐브 100개 생성하기

플라즈밍 2018. 7. 8. 18:13
반응형



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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class CubeGroupGenerator : MonoBehaviour
{
    public Vector3 position = new Vector3(10.0f, 0.0f, 0.0f);
    //정육각형 큐브를 쌓는데 for문에 사용할 반복인수로 vector3 사용
    public Vector3 count = new Vector3(10f, 10f, 10f);
 
    public void Awake()
    {
        Generator(count, position);
        OneCubeGenerator();
    }
 
    private static void Generator(Vector3 count, Vector3 position)
    {
        //레이어 마스크를 일딴 가져옴 그러기 위해서는 LayerMask를 유니티에서 추가해야됨
        //layer는 int형을 사용한다. LayerMask.NameToLayer("문자열");
        var layer = LayerMask.NameToLayer("Shootable");
        Transform parent = new GameObject().transform;
        GameObject newCube = null;
        for (int x = 0; x < count.x; x++)
        {
            for (int y = 0; y < count.y; ++y)
            {
                for (int z = 0; z < count.z; ++z)
                {
                    //실제 물체로 만듬
                    newCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
                    //위치,이름(GameObject.name),컴포넌트(GameObject.AddComponent<...>()),
                    //부모(transform.SetParent(GameObject.transform)),레이어 설정
                    newCube.transform.position = new Vector3(x, y, z);
                    newCube.name = string.Format("Cube ({0}, {1}, {2})", x, y, z);
                    newCube.AddComponent<Rigidbody>();
                    //부모설정을 왜 transform을 거처가지?
                    newCube.transform.SetParent(parent);
                   
                    newCube.layer = layer;
                }
            }
        }
        //string.Format("{0}{1}{2}..{n}",var1,var2,..,var n)
        parent.name = string.Format("Cube gruops :{0}x{1}x{2}", count.x, count.y, count.z);
        parent.position = position;
        parent.gameObject.layer = layer;
    }
    private void OneCubeGenerator()
    {
        GameObject NewOneCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
        NewOneCube.transform.position = new Vector3(-155);
        NewOneCube.name = "parent";
        GameObject NewChildCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
        // NewOneCube.transform.SetParent(NewChildCube.transform);
        NewChildCube.transform.SetParent(NewOneCube.transform);
        
    }
cs


반응형