我正在制作无限公路游戏。我正在将对象池用于道路和敌方对象。道路运行良好,但我遇到了敌人的问题,我可以从池中添加敌人,但我不能将敌人的物体返回到池中。
public void CreateEnemy( EnemyPool pool, int roadLenght, Vector3 startPos , int numberOfEnemies, int enemyType )
{
enemy = new Transform[numberOfEnemies];
enemyIndex = new int[numberOfEnemies];
currentRoadLenght = roadLenght;
//I add enemies along the length of the path. Path Lenght is randomly generated.
currentEnemyNumber = numberOfEnemies;
int arrayedEnemyObject = 0;
for( int i = 0; i < roadLenght; i++ )
{
Vector3 pos = startPos + new Vector3(0, 1, i * 15);
for( int j = 0; j < numberOfEnemies; j++ )
{
Transform obj = pool.PullEnemyFromPool(enemyType);
obj.position = pos;
obj.gameObject.SetActive(true);
enemy[j] = obj;
enemyIndex[j] = enemyType;
Debug.Log(j);
pos.z += 3;
arrayedEnemyObject++;
}
if( arrayedEnemyObject == numberOfEnemies )
{
arrayedEnemyObject = 0;
i += enemyObjectDistance;
}
}
}
public void DestroyEnemy( EnemyPool objectPooler )
{
if (enemy != null)
{
int destroyedObj = 0;
for( int i = 0; i < currentRoadLenght; i++ )
{
for( int j = 0; j < currentEnemyNumber; j++ )
{
Transform obj = enemy[j];
obj.gameObject.SetActive( false );
objectPooler.AddEnemyToPool( enemyIndex[j], obj );
destroyedObj++;
}
if( destroyedObj == currentEnemyNumber )
{
destroyedObj = 0;
i += enemyObjectDistance;
}
}
enemy = null;
}
}
我的敌人池脚本
public class EnemyPool : MonoBehaviour
{
private GameObject[] enemyObjects;
private List<Transform>[] enemyObjectsPool;
public void FillPool( GameObject[] enemyObjects , int size )
{
this.enemyObjects = enemyObjects;
Vector3 pos = Vector3.zero;
Quaternion tilt = Quaternion.identity;
GameObject obj;
enemyObjectsPool = new List<Transform>[enemyObjects.Length];
for ( int i = 0; i < enemyObjects.Length; i++ )
{
enemyObjectsPool[i] = new List<Transform>();
for( int j = 0; j < size; j++ )
{
obj = Instantiate( enemyObjects[i], pos, tilt ) as GameObject;
obj.SetActive( false );
enemyObjectsPool[i].Add( obj.transform );
}
}
}
public void AddEnemyToPool( int index, Transform obj )
{
enemyObjectsPool[index].Add (obj);
}
public Transform PullEnemyFromPool( int index )
{
Transform obj;
if( enemyObjectsPool[index].Count <= 0 )
{
obj = ( Instantiate( enemyObjects[index], Vector3.zero, Quaternion.identity ) as GameObject ).transform;
}
else
{
obj = enemyObjectsPool[index][0];
enemyObjectsPool[index].RemoveAt (0);
}
return obj;
}
}