unity 초식 추가 게임objectpool 대상 탱크
여기에 스스로 일반적인 대상 지류를 썼다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameObjectPool : MonoBehaviour where T : class {
private T m_resGameObj ;
private GameObject m_componentParent;
public delegate void OnCall();
public delegate void OnCall(T0 arg0);
public OnCall OnRecycle = null;
public OnCall OnNew = null;
public OnCall OnInitialize = null ;
private List m_pool = new List() ;
private List m_usePool = new List();
public GameObjectPool(T resObj) {
m_resGameObj = resObj;
}
public GameObjectPool(GameObject parent) {
m_componentParent = parent;
}
public int Length() {
return m_pool.Count;
}
public T0 get() where T0 : class {
T0 obj = null ;
if (m_pool.Count 0) {
obj = m_pool[m_pool.Count-1] as T0;
m_usePool.Add(m_pool[m_pool.Count-1]);
m_pool.RemoveAt(m_pool.Count-1);
}
else {
if (this.OnNew != null) {
this.OnNew.Invoke();
}
Debug.Log("~~~~ type os " + typeof(Component) + " dafdafada " + typeof(T));
if (m_resGameObj != null && typeof(GameObject) == m_resGameObj.GetType()) {
obj = Instantiate(m_resGameObj as GameObject) as T0;
m_usePool.Add(obj as T);
}
else if (m_componentParent != null && typeof(Component).IsAssignableFrom(typeof(T) ) ) {
obj = m_componentParent.AddComponent(typeof(AudioSource)) as T0;
m_usePool.Add(obj as T);
Debug.Log("~~~~ new a obj , current used count is " + m_usePool.Count);
}
else {
//TODO:
}
}
if (this.OnInitialize != null) {
this.OnInitialize.Invoke();
}
return obj ;
}
public void Recycle(T0 obj) where T0: class {
if (obj == null) {
return ;
}
for (int i = 0 ; i < m_usePool.Count ; ++i) {
if (obj == m_usePool[i]) {
m_usePool.Remove(obj as T);
Debug.Log("~~~~ remove usepool " + m_usePool.Count );
}
}
m_pool.Add(obj as T);
if (this.OnRecycle != null) {
this.OnRecycle.Invoke();
}
Debug.Log("~~~~ current pool is " + m_pool.Count );
}
public ListGetAllUseObj() {
return m_usePool;
}
public ListGetAllUnUsedObj() {
return m_pool;
}
}
예를 들어 여기서 나는 소리의 제어에 사용된다. 나는 sounds Manager를 가지고 모든 음향과 배경 음악의 재생을 제어한다. 그러나 음향은 여러 개를 동시에 재생할 수 있다. 이럴 때 여러 개의audio Source를 만들어서 서로 다른 음악을 동시에 재생해야 한다.
사용:
private GameObjectPool m_objPool ;
void Awake(){
DontDestroyOnLoad(this);
m_objPool = new GameObjectPool(this.gameObject);
}
public void playSounds(string clipName) {
StartCoroutine(poolToPlaySounds(clipName));
}
IEnumerator poolToPlaySounds(string clipName) {
AudioSource audio = m_objPool.get();
audio.loop = false ;
singlePlaySounds(clipName, audio);
yield return new WaitForSeconds(audio.clip.length);
m_objPool.Recycle(audio);
}
소리를 재생할 때 프로세스를 시작합니다. Objectpool에서 Audio Source의component를 가져옵니다. 대상 탱크에 비어 있지 않으면 새로운 리셋을 만듭니다. Simgleplaysounds는 제가 직접 쓴 방법입니다. 그 논리는 보통 clip을 Audio에 값을 부여하고 재생하는 것입니다. 이 클립의 재생 시간이 길면 이 프로세스에 delay 시간을 설정할 수 있습니다.재생 시간이 끝나면, 다음에 다시 사용할 수 있도록 새로 만든 오디오 소스 대상을 저장합니다.