情况:我指的是项目的教程,代码中有一个对象池概念.
问题:在我编写生成平台(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 QueueobjectQueue; void Start () { objectQueue = new Queue (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; } } }
提前致谢.
确保队列不为空.
if(objectQueue.Count != 0) { 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(); } }