我正在尝试通读字典并获取其中的所有值,然后检查字典位置中的值是否等于(A)单击按钮时 如果字典中的值以(A)结尾,则打印“正确”字样,否则“打印错误”
但是当我点击按钮时会发生这种情况,即打印每个值的正确性和不正确性。所以它确实找到了正确的答案和错误的答案,但我只需要打印出正确的错误
问题出现在OnGUI函数中。
代码允许随机键,这些键是在按钮点击时选择的问题,其值是作为按钮显示的答案,然后单击按钮。正确答案是以(A)结尾的值。单击显示值名称的按钮,您将检查是否选择了正确的答案,但是它有轻微的问题。它打印出所选键中每个值的正确性和不正确性
这是整个代码
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class testQuestions : MonoBehaviour {
Dictionary<string, string[]> dictionary = new Dictionary<string, string[]>();
string []vl ;
string ky;
int Qnum;
string A;
int indx;
// Use this for initialization
void Start () {
dictionary.Add("ups", new string[] {"updegree", "popup (A)"});
dictionary.Add("down aroud the place like this ", new string[] {"sun", "bun(A)","art"});
dictionary.Add("left", new string[] {"higi (A)", "migi"});
dictionary.Add("right", new string[] {"een", "yyo(A)"});
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown("q"))
{
GenerateRandoms();
}
}
void GenerateRandoms()
{
string[] keys = new string[dictionary.Count];//get the dictionary count and store in array
dictionary.Keys.CopyTo(keys, 0);
var index = Random.Range(0, keys.Length);
var key = keys[index];
var value = dictionary[key];
ky= key;
vl = value;
foreach (string ku in value)
{
// create buttons with the ku text as the button text
indx = index;
Qnum +=1;
A = ku;
}
//---------- remove each after answer button click
//dictionary.Remove(key); // remove key after it is already displayed. this must only be exicuted at the end of the function
}
void OnGUI ()
{
int charlength = 0;
foreach(char NumOfChar in ky)
{
charlength ++;
}
GUI.TextArea(new Rect (0,0,charlength*10 + 100,20),"Key is " + ky /*+ " value is " + string.Join(",", vl) + " position is " +int.Parse(indx.ToString())*/);
for (int i = 0; i < dictionary[dictionary.Keys.ElementAt(indx)].Length; i++)
{
if (GUI.Button (new Rect(0, 30 + Screen.height-Screen.height + 40* i, 100, 20),dictionary[dictionary.Keys.ElementAt(indx)][i]))
{
for (int i2 = 0; i2 < dictionary[dictionary.Keys.ElementAt(indx)].Length; i2++)
{
string Answer = dictionary[dictionary.Keys.ElementAt(indx)][i2];
if (Answer.EndsWith("(A)"))
{
print ("Correct");
}
else
{
print ("Incorrect");
}
}
}
}
}
}
答案 0 :(得分:0)
我假设您正在加载表单的可用答案,可能是带有按钮的标签或按钮文本。无论哪种方式,当您加载答案时,使用“A”设置正确按钮的标签属性。如果单击按钮的标签有“A”,则表示正确。
改变这种简单的东西,很容易适应你已经拥有的结构,比试图制造本身存在缺陷的东西要好得多
在按钮的事件处理程序中,单击这样的内容应该起作用:
void ButtonClck(object sender, eventargs e)
{
Button clickedbutton = (Button)sender;
if ((string)clickedbutton.Tag = "A")
{
print ("Correct");
}
else
{
print ("Incorrect");
}
}
答案 1 :(得分:0)
实现此目的的方法是在初始按钮单击事件之后使用if语句。检查该按钮获取其文本的来源是否正确答案。
if (GUI.Button (new Rect(0, 30 + Screen.height-Screen.height + 40* i, 100, 20),dictionary[dictionary.Keys.ElementAt(indx)][i]))
{
if (dictionary[dictionary.Keys.ElementAt(indx)][i].EndsWith ("(A)"))
{
print ("Correct");
}
else
{
print ("Incorrect");
}
}