Yes thats prob it. Here are the codes.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelGrid : MonoBehaviour {
public static LevelGrid Instance { get; private set; }
[SerializeField] private Transform gridDebugObjectPrefab;
private GridSystem gridSystem;
private void Awake() {
if (Instance != null) {
Debug.LogError("There is more than one LevelGrid!" + transform + " - " + Instance);
Destroy(gameObject);
return;
}
Instance = this;
gridSystem = new GridSystem(10, 10, 2f);
gridSystem.CreateDebugObjects(gridDebugObjectPrefab);
}
public void AddUnitAtGridPosition(GridPosition gridPosition, Unit unit) {
GridObject gridObject = gridSystem.GetGridObject(gridPosition);
gridObject.AddUnit(unit);
}
public List<Unit> GetUnitListAtGridPosition(GridPosition gridPosition) {
GridObject gridObject = gridSystem.GetGridObject(gridPosition);
return gridObject.GetUnitList();
}
public void RemoveUnitAtGridPosition(GridPosition gridPosition, Unit unit) {
GridObject gridObject = gridSystem.GetGridObject(gridPosition);
gridObject.RemoveUnit(unit);
}
public void UnitMovedGridPosition(Unit unit, GridPosition fromGridPosition, GridPosition toGridPosiiton) {
RemoveUnitAtGridPosition(fromGridPosition, unit);
AddUnitAtGridPosition(toGridPosiiton, unit);
}
public GridPosition GetGridPosition(Vector3 worldPosition) => gridSystem.GetGridPosition(worldPosition);
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GridSystem {
private int width;
private int height;
private float cellSize;
private GridObject[,] gridObjectArray;
public GridSystem(int width, int height, float cellSize) {
this.width = width;
this.height = height;
this.cellSize = cellSize;
gridObjectArray = new GridObject[width, height];
for (int x = 0; x < width; x++) {
for (int z = 0; z < height; z++) {
GridPosition gridPosition = new GridPosition(x, z);
gridObjectArray[x, z] = new GridObject(this, gridPosition);
}
}
}
public Vector3 GetWorldPosition(GridPosition gridPosition) {
return new Vector3(gridPosition.x, 0, gridPosition.z) * cellSize;
}
public GridPosition GetGridPosition(Vector3 worldPosition) {
return new GridPosition(
Mathf.RoundToInt(worldPosition.x / cellSize),
Mathf.RoundToInt(worldPosition.y / cellSize)
);
}
public void CreateDebugObjects(Transform debugPrefab) {
for (int x = 0; x < width; x++) {
for (int z = 0; z < height; z++) {
GridPosition gridPosition = new GridPosition(x, z);
Transform debugTransform = GameObject.Instantiate(debugPrefab, GetWorldPosition(gridPosition), Quaternion.identity);
GridDebugObject gridDebugObject = debugTransform.GetComponent<GridDebugObject>();
gridDebugObject.SetGridObject(GetGridObject(gridPosition));
}
}
}
public GridObject GetGridObject(GridPosition gridPosition) {
return gridObjectArray[gridPosition.x, gridPosition.z];
}
}