본문 바로가기
개발/C#

유니티 C# 최적화 기법 Object Pooling 오브젝트 풀링 간단 사용법

by SPNK 2022. 6. 15.
반응형

오브젝트 풀링이란?

오브젝트 풀링은 프로젝트를 최적화하고 게임 오브젝트를 빠르게 생성하고 파괴해야 할 때 CPU에 가해지는 부담을 줄이기 위해 사용합니다.

 

  • 코드 작성
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectPooling : MonoBehaviour
{
    public GameObject prefab; //생성할 프리팹

    public List<GameObject> prefabList = new List<GameObject>(); //프리팹을 보관할 리스트

    public int index = 0; //리스트에서 순서대로 생성하기 위한 값

    void Awake()
    {
        for (int i = 0; i < 10; i++)
        {
            GameObject monster = Instantiate(prefab); //프리팹 생성

            monster.transform.localPosition = Vector3.zero; //좌표값 초기화
            monster.transform.localRotation = Quaternion.identity; //회전값 초기화
            monster.transform.localScale = Vector3.one; //크기값 초기화

            monster.gameObject.SetActive(false); //비활성화 시키기

            prefabList.Add(monster); //생성 후 리스트에 프리팹 보관
        }
    }

    void ExampleUse(Vector3 pos)
    {
        if (index > prefabList.Count) index = 0; //리스트 순서대로 생성

        prefabList[index].transform.position = pos; //해당 위치로 프리팹 이동
        prefabList[index].SetActive(true); //프리팹 켜기

        index++; //다음 리스트 생성 번호로 이동
    }
}

 


참고할만한 글

 

 

유니티 C# 특정 값을 제외한 랜덤 값 구하기 Unity Random Value Generator

코드 작성 using UnityEngine; using System.Collections.Generic; public class RandomNumberGenerator : MonoBehaviour { private List exclusionList = new List() { 2, 3, 5, 6 }; //제외할 값 private int GenerateRandomNumber(int min, int max) { int randomV

parksh3641.tistory.com

 

 

유니티 C# 플레이어 추적하는 AI 간단 구현

코드 작성 using UnityEngine; public class MonsterTracking : MonoBehaviour { public Transform player; public float speed = 5f; public float range = 10f; void Update() { float distance = Vector3.Distance(transform.position, player.position); if (distance

parksh3641.tistory.com

 

반응형

댓글