Let’s say you have a data structure representing a quiz question…
[System.Serializable]
public struct QuizQuestion {
public string question;
public string answer1;
public string answer2;
public string answer3;
public string answer4;
public string correctAnswer;
}
…And you have some kind of “QuizData” ScriptableObject that acts as a container for all of your quiz questions…
public class QuizData : ScriptableObject {
public QuizQuestion[] questions;
}
…And you add these questions to your QuizData (through the inspector or otherwise):
new QuizQuestion {
question = "What is 2+2?",
answer1 = "3",
answer2 = "5",
answer3 = "4",
answer4 = "6",
correctAnswer = "4"
},
new QuizQuestion {
question = "What color is the sky?",
answer1 = "Orange",
answer2 = "Blue",
answer3 = "Green",
answer4 = "Purple",
correctAnswer = "Blue"
},
new QuizQuestion {
question = "What do you put in a toaster?",
answer1 = "Toast",
answer2 = "Forks",
answer3 = "Onions",
answer4 = "Bread",
correctAnswer = "Bread"
}
You’d likely want to have some kind of “QuizDataSaver” class that’s responsible for serializing/de-serializing your QuizData to/from JSON and saving/loading it to/from your database:
public class QuizDataSaver {
public void SaveData(QuizData quizData) {
//Convert the QuizData to a JSON string.
string jsonData = JsonUtility.ToJson(quizData);
//Save the jsonData to your database using the Firebase REST API...
}
public void LoadData(QuizData quizData) {
string jsonData = //Load the JSON data from your database using the REST API...
//Overwrite a QuizData instance with the data from the database.
JsonUtility.FromJsonOverwrite(jsonData, quizData);
}
}
When you call the SaveData
method, your QuizData object will be converted into this JSON string, which you can save to your Firebase database:
{
"questions": [
{
"question": "What is 2+2?",
"answer1": "3",
"answer2": "5",
"answer3": "4",
"answer4": "6",
"correctAnswer": "4"
},
{
"question": "What color is the sky?",
"answer1": "Orange",
"answer2": "Blue",
"answer3": "Green",
"answer4": "Purple",
"correctAnswer": "Blue"
},
{
"question": "What do you put in a toaster?",
"answer1": "Toast",
"answer2": "Forks",
"answer3": "Onions",
"answer4": "Bread",
"correctAnswer": "Bread"
}
]
}
Finally, you can add a QuizData reference to your QuizManager, and use the QuizDataLoader to save/overwrite the QuizData object:
public class QuizManager : MonoBehaviour {
public QuizData quizData;
private QuizDataLoader quizDataLoader = new QuizDataLoader();
//Assume once the game starts, you want to immediately load the QuizData from the database.
void Awake() {
//This will overwrite the QuizManager's QuizData object.
quizDataLoader.LoadData(quizData);
}
}