Guys, I have problem with script for random dungeon generator. I did as it is in the videos on youtube tutorial.
but I have a problem that rooms are spawning infinite (sometimes they don’t, depends) and some people were saying in comments that they have the same issue, but none of the solutions for that were helpful. So I’m asking you, where is the problem?
The script looks like that:
RoomTemplates:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RoomTemplates : MonoBehaviour
{
public GameObject closedRoom;
public GameObject[] bottomRooms;
public GameObject[] topRooms;
public GameObject[] leftRooms;
public GameObject[] rightRooms;
}
RoomSpawner:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RoomSpawner : MonoBehaviour
{
public int openingDirection;
// 1 --> need bottom door
// 2 --> need top door
// 3 --> need left door
// 4 --> need right door
private RoomTemplates templates;
private int rand;
private bool spawned = false;
public int MaximumRooms;
void Start(){
templates = GameObject.FindGameObjectWithTag("Rooms").GetComponent<RoomTemplates>();
Invoke("Spawn", 0.1f);
}
void Spawn(){
if(spawned == false && MaximumRooms <= 10){
if(openingDirection == 1){
// Need to spawn a room with a BOTTOM door.
rand = Random.Range(0, templates.bottomRooms.Length-1);
Instantiate(templates.bottomRooms[rand], transform.position, templates.bottomRooms[rand].transform.rotation);
MaximumRooms++;
} else if(openingDirection == 2){
// Need to spawn a room with a TOP door.
rand = Random.Range(0, templates.topRooms.Length);
Instantiate(templates.topRooms[rand], transform.position, templates.topRooms[rand].transform.rotation);
MaximumRooms++;
} else if(openingDirection == 3){
// Need to spawn a room with a LEFT door.
rand = Random.Range(0, templates.leftRooms.Length);
Instantiate(templates.leftRooms[rand], transform.position, templates.leftRooms[rand].transform.rotation);
MaximumRooms++;
} else if(openingDirection == 4){
// Need to spawn a room with a RIGHT door.
rand = Random.Range(0, templates.rightRooms.Length);
Instantiate(templates.rightRooms[rand], transform.position, templates.rightRooms[rand].transform.rotation);
MaximumRooms++;
}
spawned = true;
}
}
void OnTriggerEnter2D(Collider2D other){
if(other.CompareTag("Spawnpoint")){
if(other.GetComponent<RoomSpawner>().spawned == false && spawned == false){
Instantiate(templates.closedRoom, transform.position, Quaternion.identity);
Destroy(gameObject);
}
spawned = true;
}
}
}
I tried to limit number of spawned rooms by variable “MaximumRooms” but it doesn’t work.
Can someone help?