Last active
December 7, 2022 03:37
-
-
Save FriendSea/e961a983e7f80cfdbe616356446d4d38 to your computer and use it in GitHub Desktop.
クソ雑に使えるオブジェクトプール
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using UnityEngine; | |
namespace FriendSea | |
{ | |
public static class GameObjectPool | |
{ | |
static Dictionary<GameObject, GameObject> instance2prefab = new Dictionary<GameObject, GameObject>(); | |
static Dictionary<GameObject, Stack<GameObject>> prefab2pool = new Dictionary<GameObject, Stack<GameObject>>(); | |
public static GameObject Instantiate(GameObject original, Vector3 position, Quaternion rotation, Transform parent = null) | |
{ | |
if (!prefab2pool.ContainsKey(original)) | |
prefab2pool.Add(original, new Stack<GameObject>()); | |
if (prefab2pool[original].Count <= 0) | |
{ | |
var instance = GameObject.Instantiate<GameObject>(original, position, rotation, parent); | |
instance2prefab.Add(instance, original); | |
return instance; | |
} | |
else | |
{ | |
var instance = prefab2pool[original].Pop(); | |
instance.transform.parent = parent; | |
instance.transform.SetPositionAndRotation(position, rotation); | |
instance.SetActive(true); | |
return instance; | |
} | |
} | |
public static void Destroy(GameObject gameObject) | |
{ | |
gameObject.SetActive(false); | |
prefab2pool[instance2prefab[gameObject]].Push(gameObject); | |
} | |
public static void ClearAll() | |
{ | |
foreach (var pool in prefab2pool.Values) | |
foreach (var obj in pool) | |
if (obj != null) | |
GameObject.Destroy(obj); | |
prefab2pool.Clear(); | |
instance2prefab.Clear(); | |
} | |
[RuntimeInitializeOnLoadMethod] | |
static void RegisterClear() => | |
UnityEngine.SceneManagement.SceneManager.sceneUnloaded += _ => ClearAll(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment