简体   繁体   中英

How to call array element that has bool value true unity C#

I have four buttons using the same prefab and holding 4 text elements from an array out of which only one is assigned bool value to true. I am trying to access that true element when any of false element is clicked. i want to highlight true element when the false element is clicked. can anyone please help me to achieve this functionality? using simpleobjectpool taking reference from unity quiz game tutorial Thanks

Answer Button Script

public class AnswerButton : MonoBehaviour                                 
{                           
    public Text answerText;
    private AnswerData answerData;
    private GameController gameController;
    private bool isCorrect;

void Start()
{
    gameController = FindObjectOfType<GameController>();
}

public void Setup(AnswerData data)
{
    answerData = data;
    answerText.text = answerData.answerText;
}


public void HandleClick()
{
    gameController.AnswerButtonClicked(answerData.isCorrect);
    {
        if (answerData.isCorrect)
        {

        }

        if (!answerData.isCorrect)
        {


        }

    }

Answer Data Script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class AnswerData 
{
    public string answerText;
    public bool isCorrect;
}

QuestionData Script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class QuestionData
{

   public string questionText;
   public AnswerData[] answers;
}

Game Controller Script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System;

public class GameController : MonoBehaviour
 {
   public Text questionText;
   public Text scoreDisplayText;
   public SimpleObjectPool answerButtonObjectPool;
   public Transform answerButtonParent;
   public GameObject questionPanel;
   public GameObject roundOverPanel;
   public GameObject levelsPanel;
   private DataController dataController; 
   private RoundData currentRoundData;

   private bool isRoundActive;
   private float timeBeetweenQuestions = 3.0f;

   private List<GameObject> answerButtonGameObjects = new List<GameObject>();

   private QuestionData[] questionPool;
   private int questionIndex;
   private int qNumber = 0;
   private List<int> questionIndexesChosen = new List<int>();
   public int playerScore = 0;
   public int totalQuestions;


   private static int pointAddedForCorrectAnswer;

   public AudioSource answerButtonClicked;
   public AudioSource wrongAnswerClicked;


   void Start ()
   {
            dataController = FindObjectOfType<DataController>();
            currentRoundData = dataController.GetCurrentRoundData();
            questionPool = currentRoundData.questions;

            playerScore = 0;
            questionIndex = 0;
            scoreDisplayText.text = "Score: " + playerScore.ToString();
            isRoundActive = true;
            ShowQuestion();
   }



   private void ShowQuestion()
   {
            RemoveAnswerButtons();

            QuestionData questionData = questionPool[questionIndex];
            questionText.text = questionData.questionText;

            for (int i = 0; i < questionData.answers.Length; i++)
            {


          GameObject answerButtonGameObject = 
          answerButtonObjectPool.GetObject();   

          answerButtonGameObjects.Add(answerButtonGameObject);

          answerButtonGameObject.transform.SetParent(answerButtonParent);

          AnswerButton answerButton = 
         answerButtonGameObject.GetComponent<AnswerButton>();
         AnswerButton.Setup(questionData.answers[i]);

        }
 }

 private void RemoveAnswerButtons()
 {
     while (answerButtonGameObjects.Count > 0)
     {

           answerButtonObjectPool.ReturnObject(answerButtonGameObjects[0]);
           answerButtonGameObjects.RemoveAt(0);
     }
 }

 IEnumerator TransitionToNextQuestion()

 {
        yield return new WaitForSeconds(timeBeetweenQuestions);
        ShowQuestion();
 }

 IEnumerator WaitForFewSeconds()

 {
        yield return new WaitForSeconds(timeBeetweenQuestions);
        EndRound();
 }
    IEnumerator ReturnCorrectButtonColor()
{
    Debug.Log("im correct");
    GetComponent<Button>().image.color = Color.green;
    yield return new WaitForSeconds(seconds: 2.9f);
    GetComponent<Button>().image.color = Color.white;

}

IEnumerator ReturnWrongButtonColor()
{
    Debug.Log("im wrong");
    GetComponent<Button>().image.color = Color.red;
    yield return new WaitForSeconds(seconds: 2.9f);
    GetComponent<Button>().image.color = Color.white;

}

public void AnswerButtonClicked (bool isCorrect)

{
   if (isCorrect)
    {
        playerScore += currentRoundData.pointAddedForCorrectAnswer;
        scoreDisplayText.text = "Score: " + playerScore.ToString();

        //play coorect answer sound
        answerButtonClicked.Play();
        StartCoroutine(ReturnCorrectButtonColor());
    }

    if (!isCorrect)
    {
        //play wrong answer sound 
        answerButtonClicked = wrongAnswerClicked;
        answerButtonClicked.Play();
        StartCoroutine(ReturnWrongButtonColor());
        //     buttons = GameObject.FindGameObjectsWithTag("Answer");

       //    {
      //    foreach (GameObject button in buttons)
     //    {
     //        if (button.GetComponent<AnswerButton>     
     //().answerData.isCorrect)
    //        {
   //            button.GetComponent<AnswerButton> 
   //  ().StartCoroutine(ReturnCorrectButtonColor());
   //        }
  //    }
//}
    }


        if (qNumber < questionPool.Length - 1)   /
        {
              qNumber++;
              StartCoroutine(TransitionToNextQuestion());

        }
        else
        {

              StartCoroutine(WaitForFewSeconds());
        }
}

        public void EndRound()
        {
             isRoundActive = false;
             questionPanel.SetActive(false);
             roundOverPanel.SetActive(true);

        }

       //on  button click return to main menu
       public void ReturnToMenu ()
       {
          SceneManager.LoadScene("MenuScreen");
       }



 }

In order to highlight both Wrong (the clicked one) and the Right buttons you need to have access to both buttons. This means that you can't do highlighting from HandleClick method of your Answer Button Script, as it only has access to itself, eg to the Wrong button.

The good thing is that this method notifies GameController that the button has been clicked. GameController knows about all the buttons, so it can easily highlight both buttons.

So, instead of launching your highlight subroutines from Answer Button's HandleClick, you should do this from GameController's AnswerButtonClicked: identify both the Right button and the clicked button there and launch appropriate subroutines for them.

Update:

For instance, your ReturnCorrectButtonColor would look like:

IEnumerator ReturnCorrectButtonColor( GameObject button )
{
    Debug.Log("im correct");
    button.GetComponent<Button>().image.color = Color.green;
    yield return new WaitForSeconds(seconds: 2.9f);
    button.GetComponent<Button>().image.color = Color.white;
}

so in AnswerButtonClicked you identify which button to highlight as a correct answer button and pass it as a paramter to this method:

StartCoroutine(ReturnCorrectButtonColor(correctButton));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM