Hello,
I have the following problem, i’am struggling with it and i really getting frustrated about it. So that’s why i ask this question (i really hope its not asked to often, i did look for answers on this forum but didn’t find anything that i could use).
So this what i want to do:
I have 20 game objects with a Tag called answer. I want to select max 5 (unique) answers (game objects) from the total of 20 answers. I had the following code and a lot of variations of it, but i keep getting errors.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class RandomAnswer : MonoBehaviour {
public GameObject[] AnswerList;
public GameObject[] NewAnswerList;
public int MaxAnswers = 5;
void Start()
{
AnswerList = GameObject.FindGameObjectsWithTag("answer");
}
void AnswerListCheck ()
{
while (AnswerList.Length < MaxAnswers)
{
int i = Random.Range(0, AnswerList.Length);
AnswerList.Remove(i);
}
}
}
I really hope guys can help me out.
Unless it’s totally inconvenient, it’s better to keep a collection of objects than to “find” them. I use zero “finds” in my project, because I feel like they’re messy. Expose a public list or array of gameobjects and populate the list in the inspector.
public List<GameObject> allObjects;
If your objects have an Answer script, you could keep a collection of those instead for more direct access to the properties you need. The collection should be of the type you will make use of most frequently. If that’s GameObject, then a list or array of GameObjects is fine.
To satisfy your unique randoms requirement, keep a collection of those answers you have selected, and reject any random selection which is already represented in the collection:
List<GameObject> selected = new List<GameObject>();
while ( selected.Count < 5 ) {
int randomIndex = Random.Range( 0, allObjects.Count );
if ( !selected.Contains( allObjects[randomIndex] ) )
selected.Add( allObjects[randomIndex] );
}
As long as your collection contains at least as many objects as you want (five or more) this code will safely run and terminate.