Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Question How do I select a random spawn point in Unity?

Discussion in 'Getting Started' started by WobbleDobbly, Apr 29, 2024.

  1. WobbleDobbly

    WobbleDobbly

    Joined:
    Sep 25, 2023
    Posts:
    1
    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.
     
  2. Spy-Master

    Spy-Master

    Joined:
    Aug 4, 2022
    Posts:
    847
    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
    .
     
  3. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    1,108
    Code (CSharp):
    1. using UnityEngine;
    2. public class SpawnRandom : MonoBehaviour
    3. {
    4. public GameObject[] points; // Use the editor to add spawn points and drag them onto this
    5.  
    6. public GameObject target; // Drag the object that you want to spawn onto this
    7.  
    8.     void Update()
    9.     {
    10.         if (Input.GetKeyDown(KeyCode.Space))
    11.             Instantiate(target,points[Random.Range(0,points.Length)].transform.position,Quaternion.identity);
    12.     }
    13. }