Help identifying problem with passed pathfinding Queue

Good evening everyone, this one is probably pretty simple but I’m not seeing the problem. I have structure objects that are instantiated and built in my game. The structures all have a spawner class which spawn units. Now, the spawner class is responsible for getting a path from the path finding system when it is first built by the player. This is so every unit it spawns does not have to run the path finding algorithm which saves quite a bit of resources.

However, there’s something strange happening. The path found by the spawner is passed to a unit upon that unit’s instantiation. It seems like the units are all sharing the same Queue. I know this has something to do with the queue being a reference or not but I’m not sure why this would be the case. Do I really have to grab all the nodes from the queue manually and push them into a new Queue before passing it to the instantiated unit?

I wrote a bit of debug code to print out the nodes inside of each unit’s path Queue upon instantiation, here’s what that looks like as the unit’s are spawned. This is each of there queues:

You don’t have to do it manually. You can create new Queue from the old one:

var newQueue = new Queue<Node> (oldQueue);

Sounds like the path shouldn’t be a queue!

It makes the pathing code easier to read, but requires you to create a new queue for each unit that’s following the same path. If you instead store the path in a List/Array, and let each unit keep track of which index in that path they’re moving towards, you can re-use the path.

2 Likes

Well sure I could do that and have thought about switching to a list but isn’t there a way to pass a new copy of the queue instead of a reference to the original queue?

Yeah, just do what @radwan92 suggested. That’ll work just fine.

General advice is to avoid unnecessary allocations, and creating a new queue object is definitely an allocation.

Sure. You do it like this: