Several objects, same script, different values with no duplications
I'm making a little quiz game with multiple choices for practicing. Each answer button has a random item taken from a string list. I mean, the list contains elements and with this script I "paste" a random string element from that list in the UI text box to show an answer:
public Text answerText;
[SerializeField]
private int randomAnswerIndex;
void Start () {
randomAnswerIndex = Random.Range(0, languageAnswers.Count);
answerText.text = languageAnswers[randomAnswerIndex];
}
Each answer button has this script referenced, but I'm lost in how to avoid that an item text from the list shows twice, i.e., the word "English" in two different buttons at the same time. How can I solve it? If it's with an "if" statement, how can I access to the different button texts from the script? I'm trying to use "FindGameObjectWithTag", but it doesn't work.
Thanks!
Answer by akaBase · Jul 16, 2018 at 04:06 PM
Remove it from the list.
public Text answerText;
[SerializeField]
private int randomAnswerIndex;
void Start () {
randomAnswerIndex = Random.Range(0, languageAnswers.Count);
answerText.text = languageAnswers[randomAnswerIndex];
languageAnswers.RemoveAt(randomAnswerIndex);
}
}
But I think a better way to do this would be to have a main script that you can loop through the buttons rather than have them all triggered at Start().
Thanks for the answer. The option of removing the used elements from the list doesn't work because the list is inside the script attached to every button, so each button has its personal list that acts independently from the others. I'll work in the second option. When you say 'loop' do you mean that I need to activate the buttons one after another with a coroutine? Any other help to deal with this problem will be really appreciated.
I mean something like this
public Button button1;
public Button button2;
public Button button3;
public Button button4;
void Start()
{
List<Button> buttons = new List<Button> { button1, button2, button3, button4 };
List<string> answers = SomeAnswersClass.getanswers();
for (int count = 0; count < buttons.Count - 1; count++)
{
int randIndex = $$anonymous$$athf.FloorToInt(Random.Range(0, (answers.Count - 1) + 0.5f));
buttons[count].GetComponentInChildren<Text>().text = answers[randIndex];
answers.RemoveAt(randIndex);
}
}
Your answer
Follow this Question
Related Questions
Question regarding Buttons 0 Answers
Null Reference Exception 0 Answers
NullReferenceException : Object reference not set to an instance of an object? 0 Answers
Destroy Object and Text 0 Answers