So, I’m working on my first independent project as part of the Unity Junior Programmer Course, and I’ve run into a bit of a stumper. I’m making a game where targets need to be spawned, and I’ve created 5 empty game objects as spawn points. I want them to spawn randomly, but how do I get unity to pick one of these spawn points at random and instantiate a target there? I’m new to C#, but my brain tells me to go the python route and randomly select one from a list, but I don’t know how to do that. Any help would be greatly appreciated as no solutions are coming to me at the moment.
https://docs.unity3d.com/Manual/class-Random.html
See “Choosing a Random Item from an Array”
When using an array, use .Length
. For lists, use .Count
.
using UnityEngine;
public class SpawnRandom : MonoBehaviour
{
public GameObject[] points; // Use the editor to add spawn points and drag them onto this
public GameObject target; // Drag the object that you want to spawn onto this
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
Instantiate(target,points[Random.Range(0,points.Length)].transform.position,Quaternion.identity);
}
}