freedom667
freedom667

Reputation: 29

is it possible toggle bool at editor by script? (Unity3D)

I have a GameDataEditor. I entry my questions by this but I want to toggle bool when a question asked. so if a question asked, then "asked" bool will true and never seem in game. the questions asking as random. Is it possible make it?

My GameDataEditor

I write this code but it did not work. there no any response. the bool is still false.

public void ShowQuestions()
{        
    currentRoundData = dataController.GetCurrentRoundData();
    questionPool = currentRoundData.questions;
    questionIndex = Random.Range(0, questionPool.Count);
    if (!questionPool[questionIndex].asked)
    {
        questionIndex = Random.Range(0, questionPool.Count);
        questionData = questionPool[questionIndex];
        questionDisplay.GetComponentInChildren<TextMeshProUGUI>().text = questionData.question;
    }
}

public void Close()
{
    questionPool[questionIndex].asked = true;
}

Close method is a button method.

Upvotes: 0

Views: 149

Answers (1)

zambari
zambari

Reputation: 5035

you pick a random number. if the question has been asked already, you do nothing more. if it hasn't, you pick another random number (with no reference to the previous one), and then you take THAT question. this has no chance of working.

A basic refactor would change it into something more along the lines of

while (questionPool[questionIndex].asked)  
     questionIndex = Random.Range(0, questionPool.Count);
// carry on 

But this approach has serious downside - it will basically freeze your process once it runs out of unasked questions. A more robust solution would be to create two lists. I am not sure what is the structure you use for questions, I will assome Question (but you could use 'string' if you didn't store any other data, like correct answer with the data

List<Question> questionsAsked;
List<Question> questionsNotAsked;
Question currentQuestion;

void StartQuiz()
{
  questionsAsked=new List<Question>();
  questionsNotAsked=new List<Question>();
  foreach (Question q in dataController.GetCurrentRoundData().questions)
  {
     questionsNotAsked.Add(q);
  }
}

void AskQuestion()
{
   if (currentQuestion!=null) 
   {
      questionsNotAsked.Remove(currentQuestion);
      questionsAsked.Add(currentQuestion);
   }
   if (questionsNotAsked.Count>0)
   {
       currentQuestion=questionsNotAsked[  questionIndex = Random.Range(0, questionPool.Count)];
       yourTextObject.text=qurrentQuestion.ToString(); 
   }
    else
   {
     Debug.Log("quiz ended");
   }
   currentQuestion=questionsNotAsked

}

you can skip keeping track of questions added already if you don't need them, but the important part is to copy all the questions to a temporary list first, then remove each one from the list once you've asked them. This way you are sure not to draw the same question twice. Replace 'Question' with 'string' if that's your setup

Upvotes: 1

Related Questions