情况:我指的是我的项目的教程,代码中有一个对象池的概念。
问题:发生的情况是,在我编写生成平台(PlatformManager.cs)的脚本后,我得到一个异常说,
InvalidOperationException:由于对象 System.Collections.Generic.Queue`1[UnityEngine.Transform].Peek () PlatformManager.Update () (在 Assets/Platform/PlatformManager.cs:35)的当前状态,操作无效
PlatformManager.cs 脚本:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PlatformManager : MonoBehaviour {
public Transform prefab;
public int numberOfObjects;
public float recycleOffset;
public Vector3 startPosition;
public Vector3 minSize, maxSize,minGap, maxGap;
public float minY, maxY;
private Vector3 nextPosition;
private Queue<Transform> objectQueue;
void Start () {
objectQueue = new Queue<Transform>(numberOfObjects);
for (int i = 0; i < numberOfObjects; i++) {
objectQueue.Enqueue((Transform)Instantiate(prefab));
}
nextPosition = startPosition;
for (int i = 0; i < numberOfObjects; i++) {
Transform o = (Transform)Instantiate(prefab);
o.localPosition = nextPosition;
nextPosition.x += o.localScale.x;
objectQueue.Enqueue(o);
}
}
void Update () {
if (objectQueue.Peek().localPosition.x + recycleOffset < Runner.distanceTraveled)//THIS IS THE 35TH LINE WHICH CAUSE THE ERROR
{
Transform o = objectQueue.Dequeue();
o.localPosition = nextPosition;
nextPosition.x += o.localScale.x;
objectQueue.Enqueue(o);
Recycle();
}
}
private void Recycle () {
Vector3 scale = new Vector3(
Random.Range(minSize.x, maxSize.x),
Random.Range(minSize.y, maxSize.y),
Random.Range(minSize.z, maxSize.z));
Vector3 position = nextPosition;
position.x += scale.x * 0.5f;
position.y += scale.y * 0.5f;
Transform o = objectQueue.Dequeue();
o.localScale = scale;
o.localPosition = position;
nextPosition.x += scale.x;
objectQueue.Enqueue(o);
nextPosition += new Vector3(
Random.Range(minGap.x, maxGap.x) + scale.x,
Random.Range(minGap.y, maxGap.y),
Random.Range(minGap.z, maxGap.z));
if(nextPosition.y < minY){
nextPosition.y = minY + maxGap.y;
}
else if(nextPosition.y > maxY){
nextPosition.y = maxY - maxGap.y;
}
}
}
提前致谢。