我正在关注Brackeys Quiz Game教程,但遇到了问题。此行代码出现错误“对象引用未设置为对象实例”。
factText.text = currentQuestion.fact;
我正在和一位朋友一起学习本教程,我们已经复制并粘贴了代码以确保我们的代码完全相同(她的代码有效,但我的代码无效,因此它必须是检查人员)。问题是我不知道缺少什么参考。有办法解决吗?
这是完整的错误。
NullReferenceException: Object reference not set to an instance of an object
GameManager.SetCurrentQuestion () (at Assets/GameManager.cs:37)
GameManager.Start () (at Assets/GameManager.cs:29)
这是检查员的视图。事实文本没有分配任何内容,但就我所知,我们的代码和屏幕是相同的,但它不在指南中,也不在朋友的检查器中。我确定我会丢失一些东西,但不知道还能尝试什么。
这是Question.cs的代码。
[System.Serializable]
public class Question {
public string fact;
public bool isTrue;
}
这是GameManager的完整代码。
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
public Question[] questions;
private static List<Question> unansweredQuestions;
private Question currentQuestion;
[SerializeField]
private Text factText;
[SerializeField]
private float timeBetweenQuestions = 1f;
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];
factText.text = currentQuestion.fact;
unansweredQuestions.RemoveAt(randomQuestionIndex);
}
IEnumerator TransitionToNextQuestion()
{
unansweredQuestions.Remove(currentQuestion);
yield return new WaitForSeconds(timeBetweenQuestions);
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
public void UserSelectTrue()
{
if (currentQuestion.isTrue)
{
Debug.Log("CORRECT!");
}
else
{
Debug.Log("WRONG!");
}
StartCoroutine(TransitionToNextQuestion());
}
public void UserSelectFalse()
{
if (currentQuestion.isTrue)
{
Debug.Log("CORRECT!");
}
else
{
Debug.Log("WRONG!");
}
StartCoroutine(TransitionToNextQuestion());
}
}
答案 0 :(得分:0)
“ factText”变量是“ Text”类型变量。 “ currentQuestion”变量是“ Question”类型变量。他们是不同的类型。我认为您写的是“问题”类型。您是否会分享“问题”类的代码?
答案 1 :(得分:0)
在此行中创建问题数组,但未在提供的代码中的任何地方初始化:
public Question[] questions;
因此,当ToList()方法运行时,在Start()中:
unansweredQuestions = questions.ToList<Question>();
...它将把unansweredQuestions设置为null。然后,当SetCurrentQuestion()尝试从中提取随机值时,将发生NullReferenceException:
currentQuestion = unansweredQuestions[randomQuestionIndex];
似乎缺少一些代码来初始化“问题”数组并将其填充数据。