I am currently making a Question / Answer game in unity. I want to put questions in a Mysql database and I want them to show up in my text field.
You should be able to put like 100 questions in a database and get a random question in your textfield. I hope you have an idea of what I mean.
I already followed a tutorial that allows me to add questions via the inspector like this:
But I don’t want to add them via the inspector, I want to add them via a database. I already connected a database but I have no idea how to code this.
public class QuizManager : MonoBehaviour
{
public List<QuestionAndAnswers> QnA;
public GameObject[] options;
public int currentQuestion;
public Text QuestionTxt;
private void Start()
{
generateQuestion();
}
public void correct()
{
//when you are right
QnA.RemoveAt(currentQuestion);
StartCoroutine(waitForNext());
}
public void wrong()
{
//when you answer wrong
QnA.RemoveAt(currentQuestion);
StartCoroutine(waitForNext());
}
IEnumerator waitForNext()
{
yield return new WaitForSeconds(1);
generateQuestion();
}
void SetAnswers()
{
for (int i = 0; i < options.Length; i++)
{
options[i].GetComponent<AnswerScript>().isCorrect = false;
options[i].transform.GetChild(0).GetComponent<Text>().text = QnA[currentQuestion].Answers[i];
if(QnA[currentQuestion].CorrectAnswer == i+1)
{
options[i].GetComponent<AnswerScript>().isCorrect = true;
}
}
}
void generateQuestion()
{
if(QnA.Count > 0)
{
currentQuestion = Random.Range(0, QnA.Count);
QuestionTxt.text = QnA[currentQuestion].Question;
SetAnswers();
}
else
{
Debug.Log("Out of Questions");
}
}
}
[System.Serializable]
public class QuestionAndAnswers
{
public string Question;
public string[] Answers;
public int CorrectAnswer;
}
public class AnswerScript : MonoBehaviour
{
public PlayerMovement PlayerMovement;
public bool isCorrect = false;
public QuizManager quizManager;
private void Start()
{
}
public void Answer()
{
if(isCorrect)
{
PlayerMovement.MovePlayer();
Debug.Log("Correct Answer");
quizManager.correct();
}
else
{
Debug.Log("Wrong Answer");
quizManager.wrong();
}
}
}