ktyzk7
September 25, 2019, 10:28am
1
I have Question and Answers in my game.
How can I add all the question and answers collectively given the size let’s say 100 in the inspector?
public Question[] questions;
and in the script
public class Question{
public string question;
public int answer;
}
Add [Serializable] above the Question class declaration and you can edit the array in the editor.
ktyzk7
September 25, 2019, 10:32am
3
I can edit but I want to upload all questions and answers all together via code since there is too many of them, thousands in a text file.
What does your text file look like?
ktyzk7
September 25, 2019, 10:54am
5
It’s comma separated such as;
A represents this,2
B represents that,4
…
You can parse the CSV file and place it in the array or you could use an online tool to convert the CSV to JSON and parse that with the built-in Unity JSON class.
ktyzk7
September 25, 2019, 1:34pm
7
It became kind of messy for me. I used a tutorial but I’m stuck now. LoadData and game manager code below. How can I implement it into the game?
public class LoadData : MonoBehaviour
{
void Start()
{
List<Question> quests = new List<Question>();
TextAsset Questions = Resources.Load<TextAsset>("Questions");
string[] data = Questions.text.Split(new char[] { '\n' });
for (int i = 0; i < data.Length - 1; i++)
{
string[] row = data[i].Split(new char[] { ';' });
Question q = new Question();
q.question = row[0];
int.TryParse(row[1], out q.answer);
quests.Add(q);
}
}
}
public Question[] questions;
private static List<Question> unansweredQuestions;
private Question currentQuestion;
[SerializeField]
private Text questionText;
[SerializeField]
private Text answerText;
void Start()
{
if (unansweredQuestions == null || unansweredQuestions.Count == 0)
{
unansweredQuestions = questions.ToList<Question>();
}
SetCurrentQuestion();
}
void SetCurrentQuestion()
{
int randomQuestionIndex = Random.Range(0, unansweredQuestions.Count);
currentQuestion = unansweredQuestions[randomQuestionIndex];
questionText.text = currentQuestion.question;
answerText.text = currentQuestion.answer.ToString();
}
It looks like you’ve basically got it. Take the code from LoadData’s “Start”, put it into a function in your other class, and at the end of it, put:
questions = quests.ToArray();
ktyzk7
September 25, 2019, 3:18pm
9
Gives an error “Object reference not set to an instance of an object” for the below line.
string[] data = Questions.text.Split(new char[] { '\n' });
ktyzk7
September 25, 2019, 3:57pm
10
I solved it by simply dragging the file in the inspector. It works great! Thank you for your help!