85 lines
2.9 KiB
C#
85 lines
2.9 KiB
C#
using System.IO;
|
|
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
namespace InterfaceOff
|
|
{
|
|
[System.Serializable] public struct TriviaQuestion
|
|
{
|
|
/* Disables name warnings because of JSON serialization */
|
|
|
|
// ReSharper disable once InconsistentNaming
|
|
public string question;
|
|
|
|
// ReSharper disable once InconsistentNaming
|
|
public string[] choices;
|
|
|
|
// ReSharper disable once InconsistentNaming
|
|
public string answer;
|
|
}
|
|
|
|
[System.Serializable] public struct TriviaSet
|
|
{
|
|
/* Disables name warnings because of JSON serialization */
|
|
|
|
// ReSharper disable once InconsistentNaming
|
|
public TriviaQuestion[] questions;
|
|
}
|
|
|
|
public class TriviaWindow : WindowBase
|
|
{
|
|
private static TriviaSet Trivia;
|
|
|
|
private static Vector2[] Positions { get; } =
|
|
{
|
|
new(-110, 30f),
|
|
new(110f, 30f),
|
|
new(-110, -60),
|
|
new(110f, -60)
|
|
};
|
|
|
|
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
|
|
private static void LoadTriviaSet()
|
|
{
|
|
string path = Application.dataPath + "/Resources/Trivia.json";
|
|
string json = File.ReadAllText(path);
|
|
|
|
Trivia = JsonUtility.FromJson<TriviaSet>(json);
|
|
}
|
|
|
|
public override void OnWindowInstantiation()
|
|
{
|
|
/* Fetches a random question and sets it as the title */
|
|
TriviaQuestion question = Trivia.questions[Random.Range(0, Trivia.questions.Length)];
|
|
Components.InfoText.text = question.question;
|
|
Components.SetWidth(500); // Larger width is needed for this component that others
|
|
|
|
/* Adds the answer boxes */
|
|
for (int i = 0; i < 4; i++)
|
|
{
|
|
/* Creates the gameobject and fetches the needed components */
|
|
GameObject go = Instantiate(PrefabRegistry.Instance.TextButtonPrefab, transform);
|
|
Text text = go.GetComponentInChildren<Text>();
|
|
Button button = go.GetComponent<Button>();
|
|
|
|
/* Assigns needed info to the components */
|
|
text.text = question.choices[i];
|
|
|
|
RectTransform buttonTransform = button.GetComponent<RectTransform>();
|
|
buttonTransform.anchoredPosition = Positions[i];
|
|
buttonTransform.sizeDelta = new Vector2(200, 60);
|
|
|
|
/* Adds a lambda function to the button press to detect answers */
|
|
bool isCorrectButton = string.Equals(question.choices[i], question.answer);
|
|
button.onClick.AddListener(() =>
|
|
{
|
|
if (isCorrectButton)
|
|
{
|
|
DestroyWindow();
|
|
}
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|