I am making a script that for each room (in a dungeon), creates a room in all four directions, relative to the new room. The room that is created then checks if there is space to spawn, if not it shrinks and if still doesn’t fit the function ends.
To check if there are any other rooms colliding, i wait after each room to create before creating the next one. For that i made a IEnumerator function which is called on start().
private IEnumerator CreateNewRooms()
{
float newWidth;
float newLenght;
newWidth = Random.Range(4, 30);
newLenght = Random.Range(4, 30);
Debug.Log("1");
yield return StartCoroutine(DungeonGenerator.Instance.CreateRoom(newWidth, newLenght, position + Vector3.left * (width + newWidth) * 0.5f));
newWidth = Random.Range(5, 30);
newLenght = Random.Range(5, 30);
Debug.Log("2");
yield return StartCoroutine(DungeonGenerator.Instance.CreateRoom(newWidth, newLenght, position + Vector3.right * (width + newWidth) * 0.5f));
newWidth = Random.Range(5, 30);
newLenght = Random.Range(5, 30);
Debug.Log("3");
yield return StartCoroutine(DungeonGenerator.Instance.CreateRoom(newWidth, newLenght, position + Vector3.back * (lenght + newLenght) * 0.5f));
newWidth = Random.Range(5, 30);
newLenght = Random.Range(5, 30);
Debug.Log("4");
yield return StartCoroutine(DungeonGenerator.Instance.CreateRoom(newWidth, newLenght, position + Vector3.forward * (lenght + newLenght) * 0.5f));
}
Before each function i Debug a number to check if the function works. I found that only function “1” and “2” are called enough times (The max amount of times a room can be spawned is 50).
Why does this happen?
EDIT:
Here is the code from DungeonGenerator.cs:
public IEnumerator CreateRoom(float width, float lenght, Vector3 position)
{
bool isValid = false;
Collider[] hitColliders = Physics.OverlapBox(
new Vector3(position.x, position.y - 3, position.z), // Position
new Vector3(width * 0.495f, 6, lenght * 0.495f), // Size
Quaternion.identity // Rotation
);
if (index < iterations)
{
while (!isValid)
{
if (
hitColliders.Length <= 0
) { isValid = true; break; }
else
{
width--;
lenght--;
}
if (width < 5 || lenght < 5)
{
yield return null;
}
}
if (isValid)
{
// Creates room gameobject
GameObject room = new GameObject("Room");
// Adds Room component
room.AddComponent<Room>();
BoxCollider trigger = room.AddComponent<BoxCollider>();
trigger.isTrigger = true;
trigger.size = new Vector3(width, 4, lenght);
trigger.center = new Vector3(0, 2, 0);
// Sets room variables
room.GetComponent<Room>().width = width;
room.GetComponent<Room>().lenght = lenght;
room.GetComponent<Room>().position = position;
room.GetComponent<Room>().floorMat = floorMat;
room.GetComponent<Room>().wallMat = wallMat;
// Adds room to list
rooms.Add(room);
index++;
}
}
}