Create grid In Unity3D
GridManager
- generate gird control
- Store grid data (position, sprit,etc)
- grid selection
public class GridManger : MonoBehaviour { [SerializeField] private int _width, _height; [SerializeField] private Tile _tilePreFab; [SerializeField] private Transform _cam; private Dictionary<Vector2, Tile> _tiles; void Start() { _cam.transform.position = new Vector3((float) _width / 2 - 0.5f, (float)_height / 2 - 0.5f, -10); GenerateGrid(); } void GenerateGrid() { _tiles = new Dictionary<Vector2, Tile>(); for (int x = 0; x < _width; x++) { for (int y = 0; y < _height; y++) { var spawnedTile = Instantiate(_tilePreFab, new Vector3(x,y), Quaternion.identity); spawnedTile.name = $"Tile {x} {y}"; var isOffset = (x % 2 == 0 && y % 2 != 0) || (x % 2 != 0 && y % 2 == 0); spawnedTile.Init(isOffset); _tiles[new Vector2(x, y)] = spawnedTile; } } } // helper function for get grid position public Tile GetTileAtPosition(Vector2 pos) { if(_tiles.TryGetValue(pos, out var tile)) { return tile; } return null; } }
Tile Manager
public class Tile : MonoBehaviour { [SerializeField] private Color _baseColor, _offsetColor; [SerializeField] private SpriteRenderer _renderer; [SerializeField] private GameObject _highlight; public void Init(bool isOffset) { _renderer.color = isOffset ? _offsetColor : _baseColor; } void OnMouseEnter() { _highlight.SetActive(true); } void OnMouseExit() { _highlight.SetActive(false); } }
- Set color in Unity inspector