using System; using System.Collections.Generic; using UnityEngine;

[Serializable] public class SerializedObjectPool where T : MonoBehaviour { public delegate void ObjPoolEvent(T obj);

public T Prefab;

public List<T> ActiveObjs = new List<T>();

public List<T> Pool = new List<T>();

[HideInInspector]
public ObjPoolEvent OnObjActivated;

[HideInInspector]
public DelegateUtl.NoArgsEvent OnObjDisabled;

public T this[int i]
{
	get
	{
		return ActiveObjs[i];
	}
	set
	{
		ActiveObjs[i] = value;
	}
}

public int Count => ActiveObjs.Count;

public SerializedObjectPool(T prefab)
{
	Prefab = prefab;
	ActiveObjs = new List<T>();
	Pool = new List<T>();
}

public T Get(Transform parent = null)
{
	if (Pool.Count > 0)
	{
		T val = Pool[Pool.Count - 1];
		Pool.RemoveAt(Pool.Count - 1);
		if ((UnityEngine.Object)val == (UnityEngine.Object)null)
		{
			Debug.LogError('Pool ' + this?.ToString() + ' contains null obj.. retrying');
			return Get(parent);
		}
		ActiveObjs.Add(val);
		val.gameObject.SetActive(value: true);
		val.transform.SetParent(parent);
		val.transform.localScale = Vector3.one;
		if (OnObjActivated != null)
		{
			OnObjActivated(val);
		}
		return val;
	}
	T val2 = UnityEngine.Object.Instantiate(Prefab, parent);
	ActiveObjs.Add(val2);
	 if (OnObjActivated != null)
	{
		OnObjActivated(val2);
	}
	return val2;
}

public void InitSize(int num, Transform parent)
{
	DisableAll();
	for (int i = 0; i < num; i++)
	{
		Get(parent);
	}
}

public void DisableAt(int index)
{
	if (index >= 0 && index < ActiveObjs.Count)
	{
		ActiveObjs[index].gameObject.SetActive(value: false);
		Pool.Add(ActiveObjs[index]);
		ActiveObjs.RemoveAt(index);
		if (OnObjDisabled != null)
		{
			OnObjDisabled();
		}
	}
}

public void DisableObj(T activeObj)
{
	int num = ActiveObjs.IndexOf(activeObj);
	if (num >= 0)
	{
		DisableAt(num);
	}
}

public void DisableAll()
{
	if (ActiveObjs != null)
	{
		for (int i = 0; i < ActiveObjs.Count; i++)
		{
			ActiveObjs[i].gameObject.SetActive(value: false);
			Pool.Add(ActiveObjs[i]);
		}
		ActiveObjs.Clear();
		if (OnObjDisabled != null)
		{
			OnObjDisabled();
		}
	}
}

public void DisableAllAndSetParent(Transform tgtParent)
{
	for (int num = ActiveObjs.Count - 1; num >= 0; num--)
	{
		ActiveObjs[num].transform.SetParent(tgtParent);
		DisableAt(num);
	}
}

public void DisableChildren(Transform xfm)
{
	for (int i = 0; i < xfm.childCount; i++)
	{
		Transform child = xfm.GetChild(i);
		if (child.gameObject.activeSelf)
		{
			T component = child.GetComponent<T>();
			if ((UnityEngine.Object)component != (UnityEngine.Object)null)
			{
				DisableObj(component);
			}
		}
	}
}

public void DetachFromPool(T obj)
{
	ActiveObjs.Remove(obj);
	Pool.Remove(obj);
}

}

C# Unity SerializedObjectPool: Efficient Object Pooling for Game Development

原文地址: https://www.cveoy.top/t/topic/o72O 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录