今回はUnityでマス目のフィールドをinstantiateで生成してみます。
はじめに
Unityのバージョンは2021.3.3f1です。下記の様な、フィールドを生成してみます。

将棋やチェスのようにフィールドのサイズが決まっている場合は画像を用意した方が早いですが、フィールドサイズが変動する場合を想定し、スクリプトで生成してみます。
作成開始
まずは「2DObject」→「Sprites」→「Square」を選択

名前をgridtileに変更して、プレハブにします。これがマス目の種(1マス)ですね。

空のオブジェクトを追加して、名前をGridFiledに。この配下にタイルを並べます。

「GridFiledManager」と言う名前でスクリプトをアタッチ。

スクリプトの中身は下記に。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GridFiledManager : MonoBehaviour { [SerializeField] private int _rows, _cols; [SerializeField] private Gridtile _gridtile; void Start() { MakeGridFiled(); } private void MakeGridFiled() { for (int row = 0; row < _rows; row++) { for (int col = 0; col < _cols; col++) { Instantiate(_gridtile, new Vector3(row, col), Quaternion.identity, transform); } } } }
パラメータでサイズを指定。

実行すると下記の様な感じに、GridFiledの配下にgridtileオブジェクトが生成されます。

マス目が並んでいますが分かりにくいので、色が交互になるようにスクリプトのループ内を変更。
private void MakeGridFiled() { for (int row = 0; row < _rows; row++) { for (int col = 0; col < _cols; col++) { Gridtile gridtile = Instantiate(_gridtile, new Vector3(row, col), Quaternion.identity, transform); if ((row + col) % 2 != 0) { gridtile.GetComponent<SpriteRenderer>().color = Color.black; } } } }
すると下記の様な感じに生成されます。

親オブジェクトの位置を下記の様にずらすと画面中央にフィールドがくるのでスクリプトで調整してみます。

あわせて、gridtileにスクリプトをアタッチして、タイルの色をパラメータで指定できるようにします。

最終的にGridFiledManagerのスクリプトは下記に
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GridFiledManager : MonoBehaviour { [SerializeField] private int _rows, _cols; [SerializeField] private Gridtile _gridtile; void Start() { MakeGridFiled(); } private void MakeGridFiled() { for (int row = 0; row < _rows; row++) { for (int col = 0; col < _cols; col++) { Gridtile gridtile = Instantiate(_gridtile, new Vector3(row, col), Quaternion.identity, transform); gridtile.ColorChange((row + col) % 2 != 0); } } transform.position = new Vector2((float)-_rows / 2 + 0.5f, (float)-_cols / 2 + 0.5f); } }
Gridtileのスクリプトは下記に。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Gridtile : MonoBehaviour { [SerializeField] private SpriteRenderer _rend; [SerializeField] private Color _baseColor, _changeColor; public void ColorChange(bool isChangeColor) { if(isChangeColor==true) { _rend.color = _changeColor; } else { _rend.color = _baseColor; } } }
if文の部分は下記でも可。
_rend.color = isChangeColor ? _changeColor : _baseColor;