Skip to content

Instantly share code, notes, and snippets.

@unity3dcollege
Created July 14, 2017 19:32
Show Gist options
  • Select an option

  • Save unity3dcollege/cf3fa667297d1f249b7f0a1e974cf287 to your computer and use it in GitHub Desktop.

Select an option

Save unity3dcollege/cf3fa667297d1f249b7f0a1e974cf287 to your computer and use it in GitHub Desktop.
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using UnityEngine;
public class QuestionCollection : MonoBehaviour
{
private QuizQuestion[] allQuestions;
private void Awake()
{
if (!File.Exists("Questions.xml"))
{
WriteSampleQuestionsToXml();
}
LoadAllQuestions();
}
private void LoadAllQuestions()
{
XmlSerializer serializer = new XmlSerializer(typeof(QuizQuestion[]));
using (StreamReader streamReader = new StreamReader("Questions.xml"))
{
allQuestions = (QuizQuestion[])serializer.Deserialize(streamReader);
}
}
public QuizQuestion GetUnaskedQuestion()
{
ResetQuestionsIfAllHaveBeenAsked();
var question = allQuestions
.Where(t => t.Asked == false)
.OrderBy(t => UnityEngine.Random.Range(0, int.MaxValue))
.FirstOrDefault();
question.Asked = true;
return question;
}
private void ResetQuestionsIfAllHaveBeenAsked()
{
if (allQuestions.Any(t => t.Asked == false) == false)
{
ResetQuestions();
}
}
private void ResetQuestions()
{
foreach (var question in allQuestions)
question.Asked = false;
}
/// <summary>
/// This method is used to generate a starting sample xml file if none exists
/// </summary>
private void WriteSampleQuestionsToXml()
{
allQuestions = new QuizQuestion[] {
new QuizQuestion { Question = "If it's noon in Boston, what time is it in New York",
Answers = new string[] { "1PM", "2PM", "Noon", "11AM" }, CorrectAnswer = 2 },
new QuizQuestion { Question = "What type of animal was Babe in the film of the same name",
Answers = new string[] { "Donkey", "Spider", "Dog", "Pig" }, CorrectAnswer = 3 },
};
XmlSerializer serializer = new XmlSerializer(typeof(QuizQuestion[]));
using (StreamWriter streamWriter = new StreamWriter("Questions.xml"))
{
serializer.Serialize(streamWriter, allQuestions);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment