- Home /
How to fix some of location have more than 1 object?
I create a random gameobject by using spot location but some of location have more than 1 object, I just want to have only 1 object in 1 location
public class QtAtRandomLocation : MonoBehaviour
{
[Header("QT Event")]
public GameObject[] objectsToSpawn;
public Transform[] spawnPoints; // An Vector3 array can also be used
public List<GameObject> spawnedObjects; // Containing all spawned Objects; Using List to simply call .Add(GameObject);
public int spawnCount; // How many objects should be spawned
private int objectIndex; // Random objectsToSpawn index
private int spawnIndex; // Random spawnPoints index
private void Start()
{
// Use this for loop to not hardcode the spawn count
for (int i = 0; i < spawnCount; i++)
{
// For each iteration generate a random index; You could make an int array containing if an object already got spawned and change the index.
objectIndex = Random.Range(0, objectsToSpawn.Length);
spawnIndex = Random.Range(0, spawnPoints.Length);
// Instantiate object
GameObject go = Instantiate(objectsToSpawn[objectIndex], spawnPoints[spawnIndex].position, Quaternion.identity);
// Add Object to spawnedObjects List
spawnedObjects.Add(go);
}
}
/// <summary>
/// Draws a Sphere at each spawnPoints position
/// </summary>
private void OnDrawGizmos()
{
Gizmos.color = Color.blue;
for (int i = 0; i < spawnPoints.Length; i++)
{
Gizmos.DrawSphere(spawnPoints[i].position, 0.5f);
}
}
}
Answer by VoidPhoenix96 · Feb 14 at 12:29 AM
Check if there’s an object in that location before creating another object with if statements
Can you explain me by example script? I try to do with List but im not good at c# enough :(
Answer by barry1251 · Feb 14 at 08:47 AM
I don't think so... If you need to add the objects in a random order, you would have to look for another way of doing it.. For example with a typical array: 'Object[]' and then you shouldn't have to fill it, just initialize –
Your answer
Follow this Question
Related Questions
Pick between two floats 2 Answers
Random element from the list 1 Answer
Random select from array and spawn 1 Answer
Can´t instantiate objects in list correctly 1 Answer
Problem with List not filling using add method in a foreach loop 1 Answer