using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; //单选答题框 public class AnserWindowCtrl : MonoBehaviour { public Toggle toggle_Prefab; public Text text_ask; public Button button_sure; public ToggleGroup toogleGroup; public PromptTextCtrl promptText; List curentToggles = new List(); UnityAction answerEvent;//答题完成事件 返回选项 UnityAction answerEventAndResult;//答题事件 返回答案和选项 Question questionData; // Start is called before the first frame update void Start() { button_sure.onClick.AddListener(ButtonSure); } /// /// 注入题库和答案 答题完成事件返回学员的选项 /// /// /// public void SetAskAndAnswer(string ask,List options,UnityAction selectOver) { this.gameObject.SetActive(true); button_sure.interactable = true; text_ask.text = ask; for (int i = 0; i < curentToggles.Count; i++)//关闭现有选项 { curentToggles[i].gameObject.SetActive(false); } for (int i = 0; i < options.Count; i++)//更新选项 { if (i > curentToggles.Count - 1) curentToggles.Add(Instantiate(toggle_Prefab.gameObject, toogleGroup.transform).GetComponent());//创建新的UI curentToggles[i].gameObject.SetActive(true); curentToggles[i].isOn = false; curentToggles[i].group = toogleGroup; curentToggles[i].GetComponentInChildren().text = options[i]; } answerEvent = selectOver; } /// /// 注入问题 和答题结束事件 /// /// /// 答题结束时调用 并传回答题结果 public void SetQuestion(Question question, UnityAction selectOver) { answerEventAndResult = selectOver; questionData = question; string ask = question.question; List options = new List(); foreach (var item in question.options) { options.Add($"{item.Key}.{item.Value}"); } SetAskAndAnswer(ask, options, null); } public void Hide() { this.gameObject.SetActive(false); } //确认 public void ButtonSure() { button_sure.interactable = false; string selectOptionText = ""; for (int i = 0; i < curentToggles.Count; i++) { if (curentToggles[i].isOn)//选中的选项 { selectOptionText = curentToggles[i].GetComponentInChildren().text; break; } } if (selectOptionText == "") //未选择选项时 无法提交 { promptText.SetPrompt(LocalizationManager.Get("请选择选项后确认"), Color.red, 2f); return; } if (answerEvent != null) { answerEvent.Invoke(selectOptionText);//返回选项 //answerEvent = null; } else if (answerEventAndResult != null)// { string xuanxiang = selectOptionText.Split('.')[0].Trim();//根据组装规则获取选项代号 answerEventAndResult.Invoke(questionData.rightOptionsKey == xuanxiang, selectOptionText); //answerEventAndResult = null; } } //选择错误时 显示答题结果 public void ShowRightResult(string msg) { promptText.SetPrompt(LocalizationManager.Format("选择错误,应{0}", msg), Color.red, 2.5f); } }