- Home /
moving an object trough a queue of points
In my dart game I need a target to move between unknown amount of points that will be fed to the script via the inspector, then return to the starting point and start again. After searching the web, I chose to do it by a public array, that will be fed into a queue. After dequeuing each point it will be enqueued again into the queue. In code, it looks like this:
public class LinearMovment : MonoBehaviour
{
public Transform[] pointsArr;
public float speed;
private Vector3 targetPoint;
private int index = 1;
private Queue points = new Queue();
void Awake()
{
foreach(Transform t in pointsArr)
{
points.Enqueue(t.position);
}
transform.position = Requeue<Vector3>(points);
targetPoint = Requeue<Vector3>(points);
}
void Update()
{
if(transform.position == targetPoint)
{
index++;
targetPoint = Requeue<Vector3>(points);
print (targetPoint);
}
float distance = Vector3.Distance(transform.position, targetPoint);
transform.position = Vector3.Lerp(transform.position, targetPoint, Time.deltaTime * speed / distance);
}
object Requeue(Queue q)
{
object o = q.Dequeue();
q.Enqueue(o);
return o;
}
T Requeue<T>(Queue q)
{
return (T)Requeue(q);
}
}
This code raised the following exception: "InvalidOperationException: operation is not valid due to the current state of the object". This exception appears to be in the Queue class line 176.
What causes this problem? How to solve it? Is it even a good way to do what I'm trying to do?
Thanks in advance.
Have you checked in the inspector to make sure pointsArr
isn't empty?
All the work to use a queue seems a bit strange. From your description, all you are doing is walking a set of waypoints. There are many posts on waypoints including some code, plus there are third party solutions like iTween (free from the Asset store) that will do a smoothed walk.
It was, in fact empty. When i switched from using array to queue i forgot that. Fixed. Thanks.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Renderer on object disabled after level reload 1 Answer
promises in unityscript for Queueing 1 Answer