So I ended up reading the code again and again last night until my brain comprehended what the create methods were doing. I managed to get it partially functional last night and I believe now “fully” functional this morning.
I believe have successfully refactored every bit of grid related code into being properly scalable in this way. And by keeping track of that information in Regiongrid, when I load I can recreate every “discovered” region.
RegionGrid function is called
public void CreateNewSector()
{
Vector3 worldPosition = MouseWorld.GetPosition();
float gridOffSet = regionCellSize / 2;
Vector2 gridLocation = new Vector2(Mathf.RoundToInt((worldPosition.x - gridOffSet) / regionCellSize),
Mathf.RoundToInt((worldPosition.y - gridOffSet) / regionCellSize));
Vector2 gridPosition = new Vector2(regionCellSize * gridLocation.x, regionCellSize * gridLocation.y);
if(!RegionList.Contains(gridLocation))
{
RegionList.Add(gridLocation);
LevelGrid.Instance.IncreaseGridSize(gridLocation);
Pathfinding.Instance.SetupNewRegion(gridLocation);
GridSystemVisual.Instance.AddNewGridVisualObjects();
}
else
{
Debug.LogError("This Region Already Exists!");
}
}
Then Levelgrid Creates positions
public void IncreaseGridSize(Vector2 region)
{
gridSystem.IncreaseGridSize(
(GridSystem<GridObject> g, GridPosition gridPosition) => new GridObject(g, gridPosition),
new Vector2 (region.x * width, region.y * height));
gridSystem.CreateNewDebugObjects(gridDebugObjectPrefab, this.transform);
}
Pathfinding creates its portion
public void SetupNewRegion(Vector2 region)
{
gridSystem.IncreaseGridSize(
(GridSystem<PathNode> g, GridPosition gridPosition) => new PathNode(gridPosition),
new Vector2 (region.x * width, region.y * height));
foreach(KeyValuePair<GridPosition, PathNode> pair in gridSystem.GetDictionary())
{
Vector3 worldPosition = LevelGrid.Instance.GetWorldPosition(pair.Key);
float raycastOffsetDistance = 5f;
if(Physics.Raycast(
worldPosition + Vector3.down * raycastOffsetDistance,
Vector3.up,
raycastOffsetDistance * 2,
obstaclesLayermask))
{
GetNode(pair.Key.x, pair.Key.y).SetIsWalkable(false);
}
}
}
And then finally visibility for the unit movement
public void AddNewGridVisualObjects()
{
foreach(KeyValuePair<GridPosition, GridObject> pair in LevelGrid.Instance.GetDictionary())
{
if(gridSystemVisualDictionary.ContainsKey(pair.Key)) continue;
Transform gridSystemVisualSingleTransform =
Instantiate(gridSystemVisualSinglePrefab, LevelGrid.Instance.GetWorldPosition(pair.Key), Quaternion.identity, this.transform);
gridSystemVisualDictionary.Add(pair.Key,gridSystemVisualSingleTransform.GetComponent<GridSystemVisualSingle>());
}
UpdateGridVisual();
}
I also refactored “validpositions” to correctly use the dictionary (ontop of just about every other array based code).
If you see anything unnecessary I forgot in these sections let me know. But I can happily say it’s working exactly as I desire at present!