randomly activate one of many gameobjects ??
I gave 18 gameobjects that I want too set to active through script. the problem is that it will be inefficient to write a script and set each one o the 18 gameobjects to true or false. so is there a way to do this using an array and randomly set them to active ??
Answer by servival · Dec 01, 2015 at 06:22 PM
This is so easy.
public GameObject[] ObjectsList; // Not only 18, this script will except any number of game objects you put here.
void Start() {
ObjectsList[Random.Range(0,ObjectsList.Length)].SetActive(true);
}
Executing that code multiple times might try to activate objects that are already active.
I gave him the base code and he can start from it.
Hello! And how to do the same, but for the random inclusion of scripts?
Answer by Jessespike · Dec 01, 2015 at 06:45 PM
using System.Linq; // Top of the script, outside of the class
public GameObject[] arrayOfGameObjects;
// Randomly activates an inactive game object
public void ActivateRandomObject()
{
GameObject selection = arrayOfGameObjects
.Where(i=>!i.activeSelf)
.OrderBy(n=>Random.value).FirstOrDefault();
// selection will be null if all game objects are already active
if (selection != null) selection.SetActive(true);
}
Thanks goes to dubbreak at Select random object in list using linq
Hello! And you do not know how to do the same, but for the random inclusion of scripts at startup?
Answer by Paulo-Melo · Nov 26, 2019 at 08:50 PM
Thank you very much ! It worked for me to set active ramdom gameobjects :)