Skip to content

Instantly share code, notes, and snippets.

@hyouuu
Created October 24, 2022 07:12
Show Gist options
  • Save hyouuu/d75d4c571385eb0ab126307be0114c10 to your computer and use it in GitHub Desktop.
Save hyouuu/d75d4c571385eb0ab126307be0114c10 to your computer and use it in GitHub Desktop.
PrefabPoolCo
using UnityEngine;
public class PrefabPoolCo : MonoBehaviour {
// singleton for easier access from other scripts
public static PrefabPoolCo one;
[Header("Settings")] public GameObject prefab;
public int initialSize = 300;
public int exhaustionSize = 30;
public int sizeToAddWhenExhausted = 100;
[Header("Debug")] public int activeCount = 0;
public int createdCount = 0;
QueuePool<GameObject> pool;
void Start() {
one = this;
// registerPrefab();
InitializePool();
}
/*
// Need to be called whenever client re-connects
public void registerPrefab() {
NetworkClient.RegisterPrefab(prefab, SpawnHandler, UnspawnHandler);
}
public void unregisterPrefab() {
NetworkClient.UnregisterPrefab(prefab);
}
// used by NetworkClient.RegisterPrefab
GameObject SpawnHandler(SpawnMessage msg) {
return Get(msg.position, msg.rotation);
}
// used by NetworkClient.RegisterPrefab
void UnspawnHandler(GameObject spawned) => Return(spawned);
*/
void OnDestroy() {
// unregisterPrefab();
}
void InitializePool() {
// create pool with generator function
// pool = new Pool<GameObject>(CreateNew, poolSize);
pool = new QueuePool<GameObject>(CreateNew, initialSize, exhaustionSize, sizeToAddWhenExhausted);
}
GameObject CreateNew() {
GameObject next = Instantiate(prefab, transform);
next.name = $"{prefab.name}_pooled_{createdCount}";
next.SetActive(false);
createdCount++;
return next;
}
// Used to take objects from pool.
// Should be used on server to get the next object
// Used on client by NetworkClient to spawn objects
public GameObject Get(Vector3 position, Quaternion rotation) {
GameObject next = pool.Get();
if (next == null) {
Debug.LogWarning("PrefabPoolCo Get next null activeCount:" + activeCount);
next = CreateNew();
pool.objects.Enqueue(next);
}
// set position/rotation and set active
next.transform.position = position;
next.transform.rotation = rotation;
next.SetActive(true);
activeCount++;
return next;
}
// Used to put object back into pool so they can be reused
// Should be used on server after unspawning an object
public void Return(GameObject spawned) {
activeCount--;
// disable object
spawned.SetActive(false);
// add back to pool
pool.Return(spawned);
Debug.Log("PrefabPoolCo Return unspawned:" + spawned.name + " activeCount:" + activeCount + " pool count:" +
pool.Count);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment