"Object reference not set to an instance of an object"但找不到检查器中缺少的对象引用



我正在关注Brackeys测验游戏教程,并遇到了问题。我会收到此代码行的错误"对象引用未设置为对象的实例"。

 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)

这是检查员的视图。事实文字没有分配给任何东西,但这不在指南中,也不是在我朋友的检查员中,所以据我所知,我们的代码和屏幕是相同的。我确定我缺少一些东西,但不知道该尝试什么。

https://i.stack.imgur.com/c8jir.jpg

这是问题的代码。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());
 }
 }

这些问题在此行中创建的问题,但在提供的代码中不会在任何地方初始化:

public Question[] questions;

so在start((中运行tolist((方法:

unansweredQuestions = questions.ToList<Question>();

...它将将UnwersweredQuestions设置为null。然后,当SetCurrentQuestion((尝试从中汲取随机值时,将发生NullReferenceException:

currentQuestion = unansweredQuestions[randomQuestionIndex];

似乎有一些缺少的代码来初始化"问题"数组并用数据填充。

" factText"变量是"文本"类型变量。" CurrentQuestion"变量是"问题"类型变量。它们是不同的类型。我认为您写了"问题"类型。您会分享"问题"类的代码?

相关内容

最新更新