Answer the question
In order to leave comments, you need to log in
How to make random generation of objects according to the coordinates given in the unity array?
There are certain places where objects are false, but there are more places than objects and they have coordinates. please tell me how to make random generation of items in predefined places in Unity????
for example, write the coordinates of places into an array, and randomly create objects in some of these places, for example, in 5 out of 10 places, how to implement this ???
Answer the question
In order to leave comments, you need to log in
In general, it's as easy as shelling pears
- as I understand it, you know how to create objects.
- how to create a list of coordinates too
The code is not exact, but simply show the principle
- cycle - by the number of objects that we want to generate.
- selects a random position in the list
- generate an object in this position
- delete this position from the list
for(i=0;i<NeededNumdersOfObject;i++)
{
int randomNumber = RandomRange(0,listOfTransforms.Count);
Instantiate(Object,listOfTransforms[randomNumber ].position,....);
listOfTransforms.RemoveAt(randomNumber)
}
If you combine everything that was written here, it will turn out like this. It seems compact and works with a bang.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Spawner : MonoBehaviour
{
public List<Transform> spawnPoints = new List<Transform>();
public List<GameObject> lootPrefabs = new List<GameObject>();
public int amountEnemies = 5;
private void Start()
{
SpawnEl();
}
public void SpawnEl()
{
for(int i=0; i < amountEnemies; i ++){
int randomNumber = Random.Range(0,spawnPoints.Count);
GameObject loot = SpawnLoot(spawnPoints[randomNumber]);
spawnPoints.RemoveAt(randomNumber);
}
}
private GameObject SpawnLoot(Transform spawnPoint)
{
var prefab = lootPrefabs[Random.Range(0, lootPrefabs.Count)];
return Instantiate(prefab, spawnPoint.position, spawnPoint.rotation);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question