Skip to content

Instantly share code, notes, and snippets.

@dskjal
Last active September 26, 2016 03:10
Show Gist options
  • Save dskjal/179cf12c0f4e8afdc251a71849d991c7 to your computer and use it in GitHub Desktop.
Save dskjal/179cf12c0f4e8afdc251a71849d991c7 to your computer and use it in GitHub Desktop.
Unity のプレハブをプールしておくコンテナ
// BEGIN MIT LICENSE BLOCK //
//
// Copyright (c) 2016 dskjal
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
// END MIT LICENSE BLOCK //
/* 使い方
public GameObject Prefab;
private InstancePool enemyPool;
void Start(){
enemyPool = new InstancePool(Prefab, 10000);
for(var i = 0; i < 100; ++i){
var e = enemyPool.GetInstance();
// 取得したインスタンスを初期化
// e.Value.Init()
}
}
// アクティブインスタンスの列挙
for(var i = 0; i < enemyPool.Count; ++i){
//enemyPool[i].Value.MyUpdate()
}
// 不要なインスタンスを返す
for(var i = 0; i < enemyPool.Count; ++i){
if(!enemyPool[i].Value.activeInHierarchy){
enemyPool.ReturnInstance(enemies[i]);
--i;
continue;
}
}
*/
using UnityEngine;
public class InstancePool {
public struct Node {
public GameObject Value;
public readonly int LocationInPool;
public Node(GameObject value, int loc) {
Value = value;
LocationInPool = loc;
}
}
private Node[] pool;
private int count;
public int Count { get { return count; } }
public int Capacity { get { return pool.Length; } }
public bool HasSurplus() { return Capacity - Count > 0; }
public InstancePool(GameObject prefab, int capacity) {
pool = new Node[capacity];
for(var i = 0; i < capacity; ++i) {
pool[i] = new Node(Object.Instantiate(prefab), i);
pool[i].Value.SetActive(false);
}
count = 0;
}
public Node GetInstance() {
Debug.Assert(Capacity > Count, "Run out of instance.");
return pool[count++];
}
public void ReturnInstance(Node item) {
Debug.Assert(count > 0, "Pool is empty.");
Debug.Assert(!item.Value.activeInHierarchy, "Returned instance is active.");
var inactive = pool[item.LocationInPool].Value;
pool[item.LocationInPool].Value = pool[--count].Value;
pool[count].Value = inactive;
}
public void ReturnInactives() {
for(var i = 0; i < count; ++i) {
if (!pool[i].Value.activeInHierarchy) {
ReturnInstance(pool[i]);
--i;
continue;
}
}
}
public Node this[int i]
{
get
{
Debug.Assert(i < Count, "Index exceeds count.");
return pool[i];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment