Tarodev

Game Grid - GridManager.cs

Jun 14th, 2021
1,309
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5.  
  6. public class GridManager : MonoBehaviour {
  7.     [SerializeField] private int _width, _height;
  8.  
  9.     [SerializeField] private Tile _tilePrefab;
  10.  
  11.     [SerializeField] private Transform _cam;
  12.  
  13.     private Dictionary<Vector2, Tile> _tiles;
  14.  
  15.     void Start() {
  16.         GenerateGrid();
  17.     }
  18.  
  19.     void GenerateGrid() {
  20.         _tiles = new Dictionary<Vector2, Tile>();
  21.         for (int x = 0; x < _width; x++) {
  22.             for (int y = 0; y < _height; y++) {
  23.                 var spawnedTile = Instantiate(_tilePrefab, new Vector3(x, y), Quaternion.identity);
  24.                 spawnedTile.name = $"Tile {x} {y}";
  25.  
  26.                 var isOffset = (x % 2 == 0 && y % 2 != 0) || (x % 2 != 0 && y % 2 == 0);
  27.                 spawnedTile.Init(isOffset);
  28.  
  29.  
  30.                 _tiles[new Vector2(x, y)] = spawnedTile;
  31.             }
  32.         }
  33.  
  34.         _cam.transform.position = new Vector3((float)_width/2 -0.5f, (float)_height / 2 - 0.5f,-10);
  35.     }
  36.  
  37.     public Tile GetTileAtPosition(Vector2 pos) {
  38.         if (_tiles.TryGetValue(pos, out var tile)) return tile;
  39.         return null;
  40.     }
  41. }
RAW Paste Data