【问题标题】:Unity how to add Lists to a List?Unity如何将列表添加到列表中?
【发布时间】:2020-01-30 17:08:23
【问题描述】:

我已经搜索了几天,但找不到解决问题的方法。

我有一个迷你问答游戏,每个问题有 3-4 个答案选项,这些选项将随机获取。

我从 CSV 获取问题和分数,但我不知道以什么结构存储它。

// kind of a structure I'm looking for
Questions[0] = [["Answer 1", 2]                
               ["Answer 2", 3]
               ["Answer 3", 1]];
Questions[1] = [...]


// my approach (pseudocode) 
List<Questions> _questions = new List<Questions>();
_questions.question.Add(["What's up?",1],["What's down?",3]);
...
public class Questions{
    public Dictionary<string,int> question = new Dictionary<string,int>();
}

【问题讨论】:

  • 您需要List&lt;Question&gt;(单数)而不是List&lt;Questions&gt;。这应该使您的设计更清晰。特别是该课程不需要所有其他问题的字典。所有Question 都不应该是它自己的文本和它的答案——也许也是某种分数,但就是这样。
  • 什么结构?一个你觉得舒服或你理解的。你可以将它们放在数据库、xml/json 文件、字典、列表、数组中。选择是你的
  • 我想从列表中随机选择一个问题并获取所有相关详细信息。我知道如何用数组在 PHP 中做到这一点,但不要在 C# 中得到它。

标签: c# unity3d arraylist


【解决方案1】:

您可以创建问题和答案对象并像这样构造它们:

public class Question {
   // The question that is asked.
   public string question;

   // All known answers
   public List<Answer> answers = new List<Answer>();
}

public class Answer {
   // The answer text
   public string answer;

   // The score awarded for this answer.
   public int score;
}

现在您可以从任何您想读取的地方读取数据并将其放入这些对象中。以下是手动创建这些对象的方法:

var question = new Question { question  = "What is the color of the sky", answers = { 
    new Answer { answer = "It is blue", score = 1},
    new Answer { answer = "It is yellow", score = 0} 
    } 
};

通过这种方式,您可以将问题及其所有答案放在一个很好的结构中进行处理。

【讨论】:

  • 哦,这与我要查找的内容非常接近,但它会引发错误。 "Assets/Quiz.cs(11,17):错误 CS1061:'Answer[]' 不包含 'Add' 的定义,并且没有可访问的扩展方法 'Add' 接受类型为 'Answer[] 的第一个参数' 可以找到(您是否缺少 using 指令或程序集引用?)"
  • 哦,是的,我只是从头顶输入了这个。您可以尝试使用 List 而不是 Answer[]。我修改了上面的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-14
相关资源
最近更新 更多