U
タブ 01基礎11 レッスン — タップで開く
08 / 11 · 9 分
基礎

コードでブロックの並びを作る

ここまでのプロジェクト

Assets/

Scenes/

Arena.unity

FloorBlocks (parent)

Scripts/

GridSpawner.cs

Prefabs/

P_Cube

すでにあるものこのレッスンで追加

cube 100 個を手作業で並べていると、午後がまるごと消えます。二重ループと Instantiate の呼び出し一つあれば、1 フレームで終わりです。

アニメーション図

x は横へ、z は画面の奥へ伸びて、一マスにつき cube が一つ落ちます。

グリッド状に生成するスクリプト

GridSpawner.cs
using UnityEngine;

public class GridSpawner : MonoBehaviour
{
    [SerializeField] private GameObject blockPrefab;
    [SerializeField] private int columns = 6;      // along X
    [SerializeField] private int rows = 6;
    [SerializeField] private float spacing = 1.5f; // metres between blocks
    [SerializeField] private Transform parent;

    void Start()
    {
        BuildGrid();
    }

    void BuildGrid()
    {
        // centre the grid on this object
        float offsetX = (columns - 1) * spacing * 0.5f;
        float offsetZ = (rows - 1) * spacing * 0.5f;

        for (int x = 0; x < columns; x++)
        {
            for (int z = 0; z < rows; z++)
            {
                Vector3 pos = new Vector3(
                    x * spacing - offsetX,
                    0.5f,                       // half the cube height
                    z * spacing - offsetZ);

                GameObject block = Instantiate(blockPrefab, pos, Quaternion.identity, parent);
                block.name = $"Block_{x}_{z}";  // readable in the Hierarchy
            }
        }
    }
}
  1. 1

    空の GameObject を作って Spawner と名付け、0、0、0 に置きます。

  2. 2

    それに GridSpawner.cs をアタッチし、P_Cube を Block Prefab のスロットへドラッグします。

  3. 3

    Blocks という別の空オブジェクトも作って Parent のスロットへ入れ、生成される cube をすべてその下にまとめます。

  4. 4

    Play を押すと、床の中央に 36 個の cube が現れます。

計算式を一度きちんと読み解く

  • x * spacing はループのカウント 0、1、2… をメートルに換算します:0、1.5、3、…。

  • offsetX を引くとグリッド全体が幅の半分だけ左にずれ、原点始まりではなく中央に揃います。

  • Instantiate の 4 番目の引数は親の Transform です。これを渡しておけば、Hierarchy がばらばらの 36 行になるのを防げます。

試してみる価値のあるバリエーション

inside the inner loop
// 1 — random colour per block
block.GetComponent<Renderer>().material.color =
    Random.ColorHSV(0f, 1f, 0.4f, 0.7f, 0.7f, 1f);

// 2 — random height, so it reads like a city
float h = Random.Range(0.5f, 4f);
block.transform.localScale = new Vector3(1f, h, 1f);
block.transform.position   = new Vector3(pos.x, h * 0.5f, pos.z);

// 3 — a wave, using the distance from the centre
float d = new Vector2(x - columns * 0.5f, z - rows * 0.5f).magnitude;
block.transform.position += Vector3.up * Mathf.Sin(d) * 0.6f;

グリッドを消す

C# スクリプト
public void ClearGrid()
{
    // backwards: still right if this ever becomes DestroyImmediate
    for (int i = parent.childCount - 1; i >= 0; i--)
        Destroy(parent.GetChild(i).gameObject);
}