
【Unity ローグライク制作#10】プログラムを分割しよう(ダンジョン生成、キャラ配置処理)
初めての方はこちら:#1 プロジェクト作成と素材のインポート
◀前の記事:#9 敵を作成してダンジョンに配置しよう
▶次の記事:#11 キャラのステータス設定と攻撃処理を作ろう
前回までのプログラムでダンジョン生成、プレイヤーと敵のランダム配置処理を作りました。
ただ、ダンジョン生成処理クラスの中へキャラクターのランダム配置処理を記載している状態です。それらの処理は役割が異なるため、役割ごとに分けると良いです。
また、分けることで以下のメリットもあります。
・一つのクラス内のコード量が減るため、可読性が向上
・クラスの役割が明確になることで、プログラムの書いてあるクラスが想像でき、保守性が向上
それでは、プログラムを書いていきましょう。
手順①:定数用のクラスを作成しよう
まずは、DungeonGeneratorにある定数を整理しましょう。
今回はタイル関係の定数をまとめるクラス「TileConstants」を作成して、以下のInvalidTilePositionを記載しましょう。

using UnityEngine;
public static class TileConstants
{
// タイルに関する定数クラス
// タイルの座標の無効値
public static readonly Vector2Int InvalidTilePosition = new Vector2Int(-1, -1);
}このように関係のあるものでまとめていくと、保守性が上がります。
手順②:DungeonGeneratorの変数を外部クラスでも取得できるようにしよう
外部でも使いたい変数は、mapとroomPosListです。
その2つの変数はprivateにしているため、DungeonGeneratorクラス以外のクラスでは値を確認することができません。
その問題を解決するために、今回はプロパティと関数を使って外部からもアクセスを許可して値を確認できるようにしていきます。
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class DungeonGenerator : MonoBehaviour
{
[SerializeField] private TileBase wallTile; // 壁のスプライト
[SerializeField] private TileBase floorTile; // 床のスプライト
// マップの大きさを設定
[SerializeField] private int mapWidth = 40;
[SerializeField] private int mapHeight = 25;
// 部屋の数
[SerializeField] private int roomCount = 5;
// 部屋サイズの範囲を設定
[SerializeField] private int minRoomSize = 4;
[SerializeField] private int maxRoomSize = 8;
[SerializeField] private int maxRoomCreateCount = 10; // 部屋作成の最大試行回数
// マップデータ(二次元配列)
private int[,] map;
//------- 追加 Start --------//
// 指定座標のマップデータを取得する関数
public int GetTileValue(int x, int y)
{
return map[x, y];
}
//------- 追加 End --------//
// 部屋の中心点を保存
private readonly List<Vector2Int> roomCenters = new List<Vector2Int>();
// タイルマップ用の変数
[SerializeField] private Tilemap wallTilemap;
[SerializeField] private Tilemap floorTilemap;
// 部屋の座標を取得
private readonly List<RectInt> roomPosList = new List<RectInt>();
//------- 追加 Start --------//
// 部屋の座標リストを外部から参照するためのプロパティ
public IReadOnlyList<RectInt> RoomPosList
{
get { return roomPosList; }
}
//------- 追加 End --------//~~ 省略 ~~
このようにプロパティや関数を作ってprivateの変数を渡してあげることによって、外部のクラスで書き換えできないようにしています。
補足:RoomPosListの型にIReadOnlyListを使用していますが、これは、読み取り専用(追加、削除不可)のインターフェースです。外部から誤って追加されないようにしています。
手順③:プレイヤーのランダム配置用のクラスを作成しよう
プレイヤーランダム配置用のクラス「PlayerSpawner」を作成しましょう。
以下のように記載してください。
using UnityEngine;
public class PlayerSpawner : MonoBehaviour
{
[SerializeField] private GameObject playerPrefab;
// プレイヤーをランダムな部屋の中にスポーンさせるメソッド
public Vector2Int SpawnPlayerInRandomRoom(DungeonGenerator dungeonGenerator)
{
// 部屋が存在しない場合は処理を終了
if (dungeonGenerator.RoomPosList.Count == 0) return TileConstants.InvalidTilePosition;
RectInt room = dungeonGenerator.RoomPosList[Random.Range(0, dungeonGenerator.RoomPosList.Count)];
int x = Random.Range(room.xMin + 1, room.xMax - 1);
int y = Random.Range(room.yMin + 1, room.yMax - 1);
Instantiate(playerPrefab, new Vector3(x + 0.5f, y + 0.5f, 0f), Quaternion.identity);
// プレイヤーが設置されたタイルの座標を設定
Vector2Int playerPositionTile = new Vector2Int(x, y);
return playerPositionTile;
}
}大部分はDungeonGeneratorから移動させましたが、以下を修正しているのでご注意ください。
①playerPrefab変数をpublicから[SerializeField]に変更
※他のコードと統一のため
②SpawnPlayerInRandomRoomの引数にDungeonGeneratorを追加
③if (roomPosList.Count == 0) return InvalidTilePosition;を
if (roomPosList.Count == 0) return TileConstants.InvalidTilePosition;
に変更
手順④:敵のランダム配置用のクラスを作成しよう
次は敵をランダム配置用のクラス「EnemySpawner」を作成しましょう。
以下のように記載してください。
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
[SerializeField] private int enemyCount = 5;
[SerializeField] private List<GameObject> enemyPrefabList = new List<GameObject>(); // エネミーオブジェクト
private readonly HashSet<Vector2Int> occupiedTilePositions = new HashSet<Vector2Int>(); // 配置済タイル座標リスト
// エネミーをランダムな部屋の中にスポーンさせるメソッド
public void SpawnEnemiesInRandomRooms(DungeonGenerator dungeonGenerator, Vector2Int playerTilePosition)
{
// Enemyのプレハブが設定されていない場合は終了
if (enemyPrefabList.Count == 0) return;
// 部屋が存在しない場合は処理を終了
if (dungeonGenerator.RoomPosList.Count == 0) return;
// プレイヤーの位置が取得できない場合は終了
if (playerTilePosition == TileConstants.InvalidTilePosition) return;
// すでに使用されているタイル座標(プレイヤー含む)を管理する
occupiedTilePositions.Clear();
occupiedTilePositions.Add(playerTilePosition);
int spawned = 0; // スポーン数
int maxTry = enemyCount * 10; // 最大トライ数(無限ループ防止)
int tryCount = 0; // トライ数
// エネミープレハブの数生成される、または、トライ数が最大トライ数を超えるまで実行
while (spawned < enemyCount && tryCount < maxTry)
{
tryCount++;
RectInt room = dungeonGenerator.RoomPosList[Random.Range(0, dungeonGenerator.RoomPosList.Count)];
int x = Random.Range(room.xMin + 1, room.xMax - 1);
int y = Random.Range(room.yMin + 1, room.yMax - 1);
Vector2Int tilePos = new Vector2Int(x, y);
int enemyIndex = Random.Range(0, enemyPrefabList.Count);
GameObject targetEnemy = enemyPrefabList[enemyIndex]; // エネミーリストからランダムでエネミーを取得
if (!targetEnemy) continue; // エネミーが取得できなければ再トライ
if (occupiedTilePositions.Contains(tilePos)) continue; // 配置済のタイルだった場合は再トライ
if (dungeonGenerator.GetTileValue(x, y) != 1) continue; // マップが床で無ければ再トライ
Instantiate(targetEnemy, new Vector3(x + 0.5f, y + 0.5f, 0f), Quaternion.identity);
occupiedTilePositions.Add(tilePos); // 配置済リストに追加
spawned++;
}
}
}
こちらもDungeonGeneratorから移動させましたが、以下を修正しているのでご注意ください。
①SpawnEnemiesInRandomRoomsの引数にDungeonGeneratorを追加
②if (playerTilePosition == InvalidTilePosition) return;を
if (playerTilePosition == TileConstants.InvalidTilePosition) return;
に変更
手順⑤:DungeonGeneratorを整理しよう
手順①、③、④で移動した処理を削除します。
削除すると以下のようになります。
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class DungeonGenerator : MonoBehaviour
{
[SerializeField] private TileBase wallTile; // 壁のスプライト
[SerializeField] private TileBase floorTile; // 床のスプライト
// マップの大きさを設定
[SerializeField] private int mapWidth = 40;
[SerializeField] private int mapHeight = 25;
// 部屋の数
[SerializeField] private int roomCount = 5;
// 部屋サイズの範囲を設定
[SerializeField] private int minRoomSize = 4;
[SerializeField] private int maxRoomSize = 8;
[SerializeField] private int maxRoomCreateCount = 10; // 部屋作成の最大試行回数
// マップデータ(二次元配列)
private int[,] map;
// 指定座標のマップデータを取得するメソッド
public int GetTileValue(int x, int y)
{
return map[x, y];
}
// 部屋の中心点を保存
private readonly List<Vector2Int> roomCenters = new List<Vector2Int>();
// タイルマップ用の変数
[SerializeField] private Tilemap wallTilemap;
[SerializeField] private Tilemap floorTilemap;
// 部屋の座標を取得
private readonly List<RectInt> roomPosList = new List<RectInt>();
// 部屋の座標リストを外部から参照するためのプロパティ
public IReadOnlyList<RectInt> RoomPosList
{
get { return roomPosList; }
}
private void MapGenerate()
{
// マップ初期化
map = new int[mapWidth, mapHeight];
// 中心点のリストを初期化
roomCenters.Clear();
roomPosList.Clear();
for (int i = 0; i < roomCount; i++)
{
CreateRoom();
}
// 通路作成
ConnectRoomsInOrder();
// タイルの表示
InstantiateTile();
}
private void CreateRoom()
{
for(int i = 0; i < maxRoomCreateCount; i++)
{
// 部屋の大きさを決める
int roomWidth = Random.Range(minRoomSize, maxRoomSize + 1);
int roomHeight = Random.Range(minRoomSize, maxRoomSize + 1);
// 部屋の位置を決める
int roomX = Random.Range(1, mapWidth - roomWidth - 1);
int roomY = Random.Range(1, mapHeight - roomHeight - 1);
// 部屋が重なっていないかチェック
if (IsOverlapping(roomX, roomY, roomWidth, roomHeight)) continue;
for (int x = roomX; x < roomX + roomWidth; x++)
{
for (int y = roomY; y < roomY + roomHeight; y++)
{
map[x, y] = 1; // 床を1で表現
}
}
// 中心点を保存
int currentX = roomX + roomWidth / 2;
int currentY = roomY + roomHeight / 2;
roomCenters.Add(new Vector2Int(currentX, currentY));
// 部屋の座標を保存
// RectInt(x座標, y座標, 幅, 高さ)
roomPosList.Add(new RectInt(roomX, roomY, roomWidth, roomHeight));
return; // 部屋作成成功で終了
}
}
private bool IsOverlapping(int roomX, int roomY, int roomWidth, int roomHeight)
{
for(int x = roomX -1; x < roomX + roomWidth + 1; x++)
{
for(int y = roomY - 1; y < roomY + roomHeight + 1; y++)
{
// マップの範囲外をチェック
if (x < 0 || x >= mapWidth || y < 0 || y >= mapHeight) continue;
// 部屋の範囲内に既に床があるかチェック
if (map[x, y] == 1)
{
return true; // 重なっている
}
}
}
return false; // 重なっていない
}
// 部屋を生成順でつなぐ
private void ConnectRoomsInOrder()
{
// 部屋が1つだけだったら、処理しない
if (roomCenters.Count < 2) return;
for (int i = 0; i < roomCenters.Count - 1; i++)
{
Vector2Int fromRoom = roomCenters[i];
Vector2Int toRoom = roomCenters[i + 1];
CarveCorridorL(fromRoom, toRoom);
}
}
private void CarveCorridorL(Vector2Int from, Vector2Int to)
{
// x軸に通路を作成
// from = 基準点からto = 目的地は左右どちら側に存在するかを確認して「1 = 床」を接地
int xStep = from.x <= to.x ? 1 : -1;
for (int x = from.x; x != to.x; x += xStep)
{
map[x, from.y] = 1;
}
// L字の曲がり角も床を置く
map[to.x, from.y] = 1;
int yStep = from.y <= to.y ? 1 : -1;
for (int y = from.y; y != to.y; y += yStep)
{
map[to.x, y] = 1;
}
// 目的地にも床を置く
map[to.x, to.y] = 1;
}
// 二次元配列(map)の内容に基づいてタイルを配置するメソッド
private void InstantiateTile()
{
// タイルマップをクリア (再生成するので必要)
wallTilemap.ClearAllTiles();
floorTilemap.ClearAllTiles();
for (int x = 0; x < mapWidth; x++)
{
for(int y = 0; y < mapHeight; y++)
{
Vector3Int pos = new Vector3Int(x, y, 0);
if (map[x, y] == 1)
{
// 床タイルを配置
floorTilemap.SetTile(pos, floorTile);
}
else
{
// 壁タイルを配置
wallTilemap.SetTile(pos, wallTile);
}
}
}
}
public void PrintMapToConsole()
{
for(int y = mapHeight - 1; y >= 0; y--)
{
string line = "";
for (int x = 0; x < mapWidth; x++)
{
line += map[x, y] == 1 ? "■" : "□";
}
Debug.Log(line);
}
}
}手順⑥:DungeonGeneratorの関数を外部クラスでも実行できるようにしよう
次はDungeonGeneratorのMapGenerate関数を外部で実行できるようにします。ダンジョン生成、キャラクターの配置処理を別のクラスで実行する設計にします。そのための対応です。
それに伴い、Start関数で実行していましたが、Start関数も削除します。
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class DungeonGenerator : MonoBehaviour
{~~ 省略 ~~
//------- 変更 Start --------//
public void MapGenerate()
//------- 変更 End --------//
{~~ 省略 ~~
MapGenerateはもともとprivateでしたが、publicに変更することで外部クラスでも使用できるようにしています。
手順⑦:ゲーム管理用のスクリプトを作成しよう
これまで、ダンジョン生成とキャラの配置スクリプトを作成しました。
今度は、それらのスクリプトを実行するゲームを管理するためのスクリプト「GameManager」を作成します。
using UnityEngine;
public class GameManager : MonoBehaviour
{
[SerializeField] private DungeonGenerator dungeonGenerator;
[SerializeField] private PlayerSpawner playerSpawner;
[SerializeField] private EnemySpawner enemySpawner;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
dungeonGenerator.MapGenerate();
Vector2Int playerTilePosition = playerSpawner.SpawnPlayerInRandomRoom(dungeonGenerator);
enemySpawner.SpawnEnemiesInRandomRooms(dungeonGenerator, playerTilePosition);
}
// Update is called once per frame
void Update()
{
}
}手順⑧:Unity側の設定をしよう
プログラムは書き終わりましたので、次はプログラムをゲームオブジェクトにアタッチしていきましょう。hierarchyでCreate Emptyを実行して空のゲームオブジェクトを3つ作成してください。
作成したゲームオブジェクトの名称を「PlayerSpawner」、「EnemySpawner」、「GameManager」に変更してださい。


PlayerSpawnerのゲームオブジェクトへPlayerSpawnerスクリプトをアタッチし、Playerの設定欄にプレイヤーのプレハブを設定してください。

EnemySpawnerのゲームオブジェクトにもEnemySpawnerスクリプトをアタッチし、EnemyPrefabListの設定欄にEnemyのプレハブを設定してください。

GameManagerのゲームオブジェクトにGameManagerスクリプトをアタッチしてください。そして、DungeonGenerator、PlayerSpawner、EnemySpawnerのゲームオブジェクトを設定してください。

手順⑨:動作確認してみよう
それでは動作確認してみましょう。
ダンジョン生成、プレイヤーと敵が配置されていれば成功です。

今回はここまでです。
次回は
・プレイヤーと敵のステータス設定
・敵のHPバー作成
・攻撃処理
を作っていきます。