Getting an Exception on Endless Runner 3D game
I referred to the tutorial series of: [Catlike Coding][1]
Situation: I am trying to implement Endless runner 3D game by referring the above tutorial. What happened is that when i implemented PlatformManager script, it says
InvalidOperationException: Operation is not valid due to the current state of the object System.Collections.Generic.Queue`1[UnityEngine.Transform].Peek () PlatformManager.Update () (at Assets/Platform/PlatformManager.cs:35)
There is a simple object pooling going on here,I searched google for days and couldn't find the answer. here is the PlatformManager.cs script:
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) {
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;
}
}
}
How can i get rid of this error? Thanks in advance. [1]: http://catlikecoding.com/unity/tutorials/runner/
Answer by DerperDoing · Mar 18, 2018 at 06:23 PM
Haven't read the whole code but that exception comes when the Queue is empty. Peek method reads the top element of the stack and when it is null it gives that exception.
Your answer
Follow this Question
Related Questions
need help in making an object pooler 1 Answer
Could I get an explanation of object pooling and how to do it? 2 Answers
I am trying to offset the camera from the player at all times even if the player moves. 0 Answers
How can I fix my object pool to continue after original pool is exhausted? 0 Answers