代碼優(yōu)化(3)
對象池
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public interface IPoolableObject{
void New();
void Respawn();
}
public class ObjectPool<T> where T : IPoolableObject, new() {
private List<T> _pool;
private int _currentIndex = 0;
public ObjectPool(int initialCapacity) {
_pool = new List<T>(initialCapacity);
for(int i = 0; i < initialCapacity; ++i) {
Spawn (); // instantiate a pool of N objects
}
Reset ();
}
public int Count {
get { return _pool.Count; }
}
public void Reset() {
_currentIndex = 0;
}
public T Spawn() {
if (_currentIndex < Count) {
T obj = _pool[_currentIndex];
_currentIndex++;
IPoolableObject ip = obj as IPoolableObject;
ip.Respawn();
return obj;
} else {
T obj = new T();
_pool.Add(obj);
_currentIndex++;
IPoolableObject ip = obj as IPoolableObject;
ip.New();
return obj;
}
}
}
use
using UnityEngine;
using System.Collections;
public class TestObject : IPoolableObject {
public void New() {
// very first initialization here
}
public void Respawn() {
// reset data which allows the object to be recycled here
}
public int Test(int num) {
return num * 2;
}
}
public class ObjectPoolTester : MonoBehaviour {
private ObjectPool<TestObject> _objectPool = new ObjectPool<TestObject>(100);
void Update () {
if (Input.GetKeyDown (KeyCode.Space)) {
? ? ? ? ? ? print("is print.");
_objectPool.Reset ();
int sum = 0;
for(int i = 0; i < 100; ++i) {
TestObject obj = _objectPool.Spawn ();
sum += obj.Test(i);
}
//Debug.Log (string.Format ("(Sum 1-to-100) *2 = {0}", sum));
}
}
}