Reputation: 1
I have 2 scripts one that check if an area is free one that spawn an object if the area is free this is to prevent overlapping checker script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpaceCheck : MonoBehaviour
{
public bool isFree = true;
public GameObject RoomParent;
void OnCollisionEnter(Collision col)
{
isFree = false;
}
void Start()
{
if(isFree == true)
{
RoomParent.SetActive(true);
}
}
void Update()
{
}
}
spawner script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RoomSpawner : MonoBehaviour
{
public List<Transform> Spawners;
public List<GameObject> Rooms;
int choosenSpawner = 0;
public GameObject SpaceCheck;
void Start()
{
choosenSpawner = Random.Range(0, Spawners.Count);
GameObject manager = GameObject.Find("RoomsManager");
RoomsManager managerProperty = manager.GetComponent<RoomsManager>();
GameObject Space = SpaceCheck;
SpaceCheck spaceProperty = Space.GetComponent<SpaceCheck>();
if (managerProperty.maxRoom > managerProperty.RoomCount && spaceProperty.isFree == true)
{
Instantiate(Rooms[Random.Range(0, Rooms.Count)], Spawners[choosenSpawner].position, Spawners[choosenSpawner].rotation);
RoomsManager.instance.AddRoomCount();
}
}
void Update()
{
}
}
Problem is that they still overlaps
here is the video of the problem: https://www.youtube.com/watch?v=mUjMUSNhDcQ
Upvotes: 0
Views: 434
Reputation: 340
This question is really vague, but here is an answer that assumes derHugo is correct, and you are asking how to pick random positions without duplicates:
You are storing your rooms inside a list, so all you have to do is check to see if the newly generated position is the same as any of the existing game objects in the list.
So first generate random floats in a new vector x, y, and z, and then check if that position is in the list of previously generated positions. If the list does not contain a gameobject with that position, then its unique, use it and add it to the list. If it isn't unique, throw it out and generate a new one until it is unique.
You'll want to check that the newly generated position is far enough away from the previously existing ones that they don't overlap, taking the size of the object into consideration.
Upvotes: 0