I've been building a quiz game that randomly picks a gameobject from a list and after a question is completed it reloads the scene for a new question however, it states this error:
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.
GameManager.Start () (at Assets/Scripts/GameManager.cs:30)
And this is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour {
public static int betul1 = 0;
public static int betul2 = 0;
public static int salah1 = 0;
public static int salah2 = 0;
public GameObject[] questions;
private static List<GameObject> unansweredQuestions;
private GameObject currentQuestion;
[SerializeField]
private float transitionTime = 1f;
void Start()
{
if (unansweredQuestions == null || unansweredQuestions.Count == 0)
{
unansweredQuestions = questions.ToList<GameObject>();
}
GetQuestion();
currentQuestion.SetActive(true);
}
void GetQuestion()
{
int randomNumber = Random.Range(0,unansweredQuestions.Count);
currentQuestion = unansweredQuestions[randomNumber];
}
IEnumerator NextQuestion()
{
unansweredQuestions.Remove(currentQuestion);
//currentQuestion.SetActive(false);
yield return new WaitForSeconds(transitionTime);
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
public void Yes()
{
if (betul1 == 1 && betul2 == 1)
{
Debug.Log("Congratulations! You're correct!");
StartCoroutine(NextQuestion());
}
if (salah1 == 1 && salah2 == 1)
{
Debug.Log("Sorry! You're wrong!");
StartCoroutine(NextQuestion());
}
if (betul1 == 1 && salah2 == 1)
{
Debug.Log("Your answer is invalid. Please fix it.");
}
if (betul2 == 1 && salah1 == 1)
{
Debug.Log("Your answer is invalid. Please fix it.");
}
}
}
I'm not sure what's wrong about it. I'm still relatively new to Unity so I would really appreciate it if you could point out what's causing this. Thank you in advance.
questions
? – Cidint randomNumber = Random.Range(0,unansweredQuestions.Count);
can throw an IndexOutOfRangeException Consider usingint randomNumber = Random.Range(0, unansweredQuestions.Count - 1);
(the max value is included inRandom.Range(min, max)
– Cid