- Home /
 
How to stop rooms from spawning on top of each other with list,How to make sure rooms don't spawn in the same place
I'm making a game that has a couple of room prefabs that are spawned once every second, next to the previously spawned room and I'm not sure how to stop them spawning on top of each other.
I tried to add their positions to a list and check if the new positions are in that list but it doesn't work
My code is here:
 public class BestScript : MonoBehaviour
 {
   private float x;
   private float y;
   private int roomCount;
   private int roomMade;
   private int trophyCount = 4;
   private bool check = true;
   private int plusOrMinus;
   private float roomSize = 10.25f;
   public List<Vector2> roomPositions = new List<Vector2>();
   private Vector2 newRoom;
   private Vector2 previousRoom;
 
   public float timer = 0;
   private float delay = 2;
 
   public GameObject[] rooms;
 
   void Start()
   {
     Instantiate(rooms[0], transform.position, Quaternion.identity);
     roomPositions.Add(new Vector2(0,0));
   }
 
   void Update()
   {
     timer += Time.deltaTime;
     if (timer > delay)
     {
       timer = 0;
       check = true;
       MakeRoom();
     }
   }
 
   void MakeRoom()
   {
     roomMade = Random.Range(1, trophyCount);
     while (check == true)
     {
       plusOrMinus = Random.Range(0,2) * 2 - 1;
       x = Random.Range(0,2) * plusOrMinus;
       if (x == 0)
       {
         y = plusOrMinus;
         newRoom = new Vector2(x,y);
         newRoom *= roomSize;
         if (roomPositions.Contains(newRoom) == false)
         {
           print("woj");
           newRoom += previousRoom;
           Instantiate(rooms[roomMade], newRoom, Quaternion.identity);
           roomPositions.Add(newRoom);
           previousRoom = newRoom;
           roomCount += 1;
           check = false;
         }
         else if(roomPositions.Contains(newRoom) == true)
         {
           print("test");
         }
       }
       else
       {
         y = 0;
         newRoom = new Vector2(x,y);
         newRoom *= roomSize;
         if (roomPositions.Contains(newRoom) == false)
         {
           newRoom += previousRoom;
           Instantiate(rooms[roomMade], newRoom, Quaternion.identity);
           roomPositions.Add(newRoom);
           previousRoom = newRoom;
           roomCount += 1;
           check = false;
         }
         else
         {
           print("test");
         }
       }
     }
   }
 }
 
              
               Comment
              
 
               
              Your answer
 
             Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How do you make a car drift in unity 2D 1 Answer
How to call OnCollisionEnter2D once when hitting multiple objects? 1 Answer
Cannot change the value of this integer that I use for array,Cannot change the value of this one. 0 Answers