- Home /
Choose random Gameobject from array?
Hi, sorry if this has been asked before, but I haven't found any answer.
I'm trying to make my script choose a random gameobject from my array.
GameObject[] spawnPoints = GameObject.FindGameObjectsWithTag("point");
How do I pick a random object from that array?
Thanks, Andreas.
Answer by clunk47 · Dec 04, 2013 at 09:26 PM
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
GameObject[] spawnPoints;
GameObject currentPoint;
int index;
void Start()
{
spawnPoints = GameObject.FindGameObjectsWithTag("point");
index = Random.Range (0, spawnPoints.Length);
currentPoint = spawnPoints[index];
print (currentPoint.name);
}
}
Thanks a lot :-) That was easier than I thought. Hehe.
Just a heads up for anyone looking at this answer in the future. Random.Range is inclusive at the upper limit, that means it COULD return spawnPoints.Length which would be out of the list's range. This isn't very likely, but it is bound to happen eventually.
Hey @andrewrobinsonunited FYI Random.Range is inclusive on both ends for floats, and inclusive-exclusive for ints
Answer by Foxsocks79 · Jan 26, 2019 at 03:13 AM
@clunk47's answer's correct. I just want to add, that I'm so often accessing random elements in arrays that I use this extension method to make it a bit less wordy.
namespace CustomArrayExtensions
{
public static class ArrayExtensions {
public static T GetRandom<T>(this T[] array) {
return array[Random.Range(0, array.Length)];
}
}
}
Then in my code I use like this:
using UnityEngine;
using CustomArrayExtensions;
public class ExampleClass : MonoBehaviour {
// Array populated in Unity Inspector
[SerializeField] private GameObject[] myArray;
public void Start() {
GameObject selectedObject = myArray.GetRandom();
}
}
Answer by Statement · Dec 04, 2013 at 09:18 PM
See this similar question which I've already answered.
(I don't mean to sound short, but, searching the exact text which you used as a caption yield answers).
Answer by MadJohny · Dec 04, 2013 at 09:19 PM
Try creating an int like this: int randomSpawn = (Random.Range(0f, spawnpoints.Lenght)); This might be wrong, but it might help you
Your answer
Follow this Question
Related Questions
Using arrays to randomly select an object 0 Answers
Random Range Seems... Unrandom 1 Answer
Store multiple random integers in an array? 4 Answers
How to know what random number is chosen 2 Answers
renderer.material doesnt work 3 Answers