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.
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);
}
}
@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();
}
}
Try creating an int like this: int randomSpawn = (Random.Range(0f, spawnpoints.Lenght));
This might be wrong, but it might help you