Hello everyone,
This is my first post, and I’m learning Unity 6 while working on a 3D tower defense game. I’m having trouble with the play mode in Unity, and I’d appreciate your insights.
In my scene, I have a GameController that includes two serialized fields, boardSize (Vector2Int(11,11)) and GameBoard. These are passed to the MapGenerator (an static class), which calls board.Initialize. This method creates tiles and generates paths across them.
The issue is that Unity’s play mode runs indefinitely when I use a Queue instead of a Stack in the FindPath function within TileSearch. I’d like to structure my code calls to show only the relevant code related to this problem.
Here’s a simplified version of the code:
// GameController
public class GameController : MonoBehaviour {
public static GameController Instance { get; private set; }
[SerializeField] Vector2Int boardSize = new Vector2Int(11, 11);
[SerializeField] GameBoard board = default;
private void Awake() {
if (Instance == null) {
Instance = this;
} else {
Destroy(gameObject);
}
}
public void InitializeGame() {
MapGenerator.Generate(board, boardSize);
}
}
// MapGenerator
public static class MapGenerator {
public static void Generate(GameBoard board, Vector2Int size) {
board.Initialize(size);
}
}
// GameBoard
public class GameBoard : MonoBehaviour {
public void Initialize(Vector2Int size) {
_tiles = new GameTile[size.x * size.y];
TileSearch.FindPaths(_tiles);
}
}
// TileSearch
public static class TileSearch {
public static void FindPaths(GameTile[] tiles) {
Stack<GameTile> searchFrontier = new();
foreach (GameTile tile in tiles) {
tile.ClearPath();
}
searchFrontier.Push(tiles[0]);
while (searchFrontier.Count > 0) {
GameTile tile = searchFrontier.Pop();
foreach (GameTile neighbor in tile.Neighbors) {
if (neighbor != null && !neighbor.IsExplored) {
searchFrontier.Push(neighbor);
}
}
}
}
}
When I replace the Stack with a Queue in FindPaths, Unity’s play mode freezes indefinitely. I suspect it’s related to pathfinding behavior or the structure of the Queue. Any help to diagnose or fix this issue would be greatly appreciated! Thank you.
Youtube Video: https://youtu.be/QLing3MiTc4