거북이처럼 코딩해도 괜찮으려나

개별연구2 : VR 실험실 - 06일차 본문

코딩/Unity

개별연구2 : VR 실험실 - 06일차

Hoooon22_코딩거북이_ 2022. 2. 21. 21:27
728x90

5일차에 이어서,,,

 

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

public class VoxelMaker : MonoBehaviour
{
    // voxel factory
    public GameObject voxelFactory;
    // size of object pool
    public int voxelPoolSize = 20;
    // object pool
    public static List<GameObject> voxelPool = new List<GameObject>();

    void Start()
    {
        // put inactiving voxel into object pool
        for (int i = 0; i < voxelPoolSize; i++)
        {
            // 1. create voxel from voxelFactory
            GameObject voxel = Instantiate(voxelFactory);
            // 2. inactive voxel
            voxel.SetActive(false);
            // 3. put voxel into object pool
            voxelPool.Add(voxel);
        }
    }

    void Update()
    {
        // 1. if click mouse
        if (Input.GetButton("Fire1"))
        { 
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hitInfo = new RaycastHit();

            // 2. if mouse locates on the floor
            if (Physics.Raycast(ray, out hitInfo))
            {
                /*
                // 3. make voxel from voxelmaker
                GameObject voxel = Instantiate(voxelFactory);
                // 4. place voxel
                voxel.transform.position = hitInfo.point;
                */

                // use object pool
                // 1. if exist voxel in object pool
                if (voxelPool.Count > 0)
                {
                    // 2. take one voxel from object pool
                    GameObject voxel = voxelPool[0];
                    // 3. activate voxel
                    voxel.SetActive(true);
                    // 4. place voxel
                    voxel.transform.position = hitInfo.point;
                    // 5. remove voxel from object pool
                    voxelPool.RemoveAt(0);
                }
            }
        }
    }
}

-> VoxelMaker.cs

복셀 풀을 이용하여 초당 프레임(FPS)를 올려준다.

 

다음으로 복셀을 자동으로 생성하는 코드를 작성한다.

짜잔