object pooling이라는 빈 게임오브젝트를 만든다.
(pooling되는 오브젝트를 넣을 폴더를 만든다고 생각하면 된다.)
object pooling(미리 저장 꺼내 쓸 수 있도록 저장소) +
singleton(다른 곳에서 호출하여 사용할 때 사용. 단순한 작업일 때는 static class를 사용할 수도 있음.)
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 60 | using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectPooling : MonoBehaviour { public static ObjectPooling instance = null; [Header("Object Pool")] public GameObject[] children; public int maxPool = 100; public List<GameObject> childPool = new List<GameObject>(); // Use this for initialization void Awake () { if(instance == null) { instance = this; } else if(instance != this) { Destroy(this.gameObject); } DontDestroyOnLoad(this.gameObject); CreatePooling(); } //오브젝트 풀에서 사용가능한 게임오브젝트 가져오는 함수 public GameObject GetChild() { for (int i = 0; i < childPool.Count; i++) { if(childPool[i].activeSelf == false) { return childPool[i]; } } return null; } //오브젝트 풀에 게임오브젝트 생성하는 함수 public void CreatePooling() { gameObject.transform.SetParent(transform); for (int i = 0; i < maxPool; i++) { GameObject child = children[Random.Range(0, children.Length)]; var obj = Instantiate<GameObject>(child, this.transform); obj.name = child + i.ToString("00"); obj.SetActive(false); childPool.Add(obj); } } } | cs |
저장된 오브젝트를 가져와서 사용하는 코드
호출 후에 호출 값이 null이 아닌지를 확인하고 생성할 위치와 방향을 정해준 후에 활성화시켜준다.
1 2 3 4 5 6 7 8 | //objectpoolng 스크립트를 호출하여 자식 생성 GameObject baby = ObjectPooling.instance.GetChild(); if(baby != null) { baby.transform.position = this.position; baby.transform.rotation = this.rotation; baby.SetActive(true); } | cs |
'programming > c#' 카테고리의 다른 글
유니티 C# and Shader Study <Basics 01 _ MathMatics Surface> static, enum, delegate (0) | 2019.12.17 |
---|---|
유니티 C# and Shader Study <Basics 01 _ Building a Graph> 지렁이 만들기 (0) | 2019.12.17 |
유니티 C# and Shader Study <Basics 01 _ GameObjects and Scripts> (0) | 2019.12.16 |
Mathf (0) | 2018.11.17 |
2018.11.13 - metaball(marching cubes)/GetVertx, try catch(예외처리), anim random(재생위치 랜덤) (0) | 2018.11.14 |