Search Unity

Exceptions in array

Discussion in 'Scripting' started by ScamTheMan, Jan 26, 2020.

  1. ScamTheMan

    ScamTheMan

    Joined:
    Oct 4, 2018
    Posts:
    75
    Hello I am making a quiz game with 1 correct and 3 wrong answers, each having a button. But with this code, sometimes I get the same answers on two or more buttons at the same time, which I don't want. How to make exception for each button to have different "WrongSymbol"?

    Code (CSharp):
    1.         int randomSymbol = Random.Range(0, 45);
    2.         ButtonText[0].text = WrongSymbol[randomSymbol];
    3.         randomSymbol = Random.Range(0, 45);
    4.         ButtonText[1].text = WrongSymbol[randomSymbol];
    5.         randomSymbol = Random.Range(0, 45);
    6.         ButtonText[2].text = WrongSymbol[randomSymbol];
    7.         randomSymbol = Random.Range(0, 45);
    8.         ButtonText[3].text = WrongSymbol[randomSymbol];
    9.         int randomButton = Random.Range(0, 3);
    10.         ButtonText[randomButton].text = WrongSymbol[currentQuestion.AnswerIndex];
     
  2. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    A very common and easy implementation is the following:

    Put all answers into a list.
    Generate a random index to select one.
    Assign the answer to a button, remove the answer from the list.

    Next, continue using the list with the remaining answers and start all over again.

    Note, that the random index will be generated using min = 0, max = number of elements in list (max is excluded when using integers, so you're fine using the .Count property of a list).

    Example: 5+5 = ?
    Answers { 12, 10, 15, 9 }
    Generate a random index, e.g. 2, select and remove answer at index 2 (which is 15).

    Remaining answers: {12, 10, 9 }
    Generate a random index, e.g. index 0.

    Remaining answers {10, 9 }
    ... and so on.

    The list gets shorter and at the same time, by removing selected answers, you'll avoid taking the same answers again (given that there are no duplicates in the source).

    This is also a very generic pattern to select a certain number of elements of N total elements. So you could write a small utility method which does exactly that.

    Similarly, you could also randomize the button collection instead and keep the answers in order (maybe right, wrong, wrong, wrong).

    Of course, some improvements can be applied, and there are also lots of other ways. But this is just to get you started.