A* Node Grid Generation Time

Hello,

I am trying to generate a node grid for my A* implementation. My SearchGrid.cs script looks like this

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SearchGrid : MonoBehaviour
{
    public Node[,] grid;

    public float nodeSize;
    public Terrain terrain;
    public LayerMask unwalkableNodesMasks;

    int gridSizeX;
    int gridSizeZ;

    void Start()
    {
        InitGrid();
    }

    void InitGrid()
    {
        gridSizeX = Mathf.RoundToInt(terrain.terrainData.size.x / nodeSize);
        gridSizeZ = Mathf.RoundToInt(terrain.terrainData.size.z / nodeSize);

        grid = new Node[gridSizeX, gridSizeZ];

        for (int x = 0; x < gridSizeX; x++)
        {
            for (int z = 0; z < gridSizeZ; z++)
            {
                Vector3 worldPosition = new Vector3(x, terrain.SampleHeight(new Vector3(x, 0, z)), z);
                bool walkable = !(Physics.CheckSphere(worldPosition, nodeSize, unwalkableNodesMasks));
                grid[x, z] = new Node(walkable, worldPosition);
            }
        }

        Debug.Log(grid[2048, 2048].nodePosition);
        Debug.Log(grid[2065, 2100].nodePosition);

        Debug.Log(grid[2048, 2048].isWalkable);
        Debug.Log(grid[2065, 2100].isWalkable);
    }
}

However this code takes a decent amount of time to run because my terrain size is 4096 x 4096 with a node size of 0.5f. How can I break this down so it executes faster?

Since you have to calculate this on the main thread, it’s going to take a while no matter what. They all have to be done one after the other…

I would suggest precalculating it before the game starts, storing the node list for serialization, instead.