【问题标题】:FindObjectOfType<Present>() Returns Null. Why is this?FindObjectOfType<Present>() 返回 Null。为什么是这样?
【发布时间】:2022-01-22 23:24:12
【问题描述】:

(是的,我知道它说这是重复的。我也知道这个错误意味着什么。我试图弄清楚为什么当前变量为空)

NullReferenceException:对象引用未设置为对象的实例。 Score.Update()

此脚本出错。显然当前变量为空,我正在尝试找出原因。

这是我的乐谱脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class Score : MonoBehaviour
{
    public TextMeshPro scoreText;
    public Present present;

    // Start is called before the first frame update
    void Start()
    {
        present = FindObjectOfType<Present>();
    }

    // Update is called once per frame
    void Update()
    {
        scoreText.text = present.score.ToString();
    }
}

这是我的 Present 脚本(带有 score 变量的脚本):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Present : MonoBehaviour
{
    public Vector2 velocity;
    private double deletionZone = 15;
    public int score = 0;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        // move to the left
        transform.Translate(velocity * Time.fixedDeltaTime);
        if (transform.position.x <= -deletionZone)
        {
            Destroy(gameObject);
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Player")
        {
            Destroy(gameObject);
            score += 10;
        }
    }
}

【问题讨论】:

  • 1) 使用调试器或其他方式找出哪个变量为空。 2) 回溯以找出 为什么 它为空。如果您发现 what 为空但不知道 为什么,请编辑您的问题,也许它会重新打开。
  • 将措辞更改为 "FindObjectOfType() retuns null 而我不明白为什么" 可能会重新打开您的问题。摆脱问题中的异常部分,并专注于您如何检查变量是否为空以及为什么您希望它不为空。
  • 你确实需要先做一些基本的调试。你甚至没有说你在哪一行得到这个错误,虽然我可以猜到。并且您声明 “在第一帧更新之前调用 Start” 而不备份:您是否设置断点来确认?
  • 没有提及创建Present 组件和/或将其附加到场景中的任何游戏对象。考虑这样做或编辑问题以包含minimal reproducible example
  • I'm trying to figure out why the present variable is null) -> Debugging your code in Unity and your external IDE

标签: c# unity3d nullreferenceexception


【解决方案1】:

我几天前解决了这个问题,但没有在这里更新。

显然 FindObjectOfType() 实际上没有返回 null,我想我在调试和发布之前做了假设。

无论如何,


而不是使用

public TextMeshPro scoreText;

这是我应该做的:

public TextMeshProUGUI scoreText;

本可以为我的 Game Jam 项目节省一天的工作时间:|

【讨论】:

  • 如果它解释了它是如何使pesent 非空的,这个答案将会得到改进
  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

我认为这是因为您使用大写 P 命名 Present 字段,它应该是小写 - present。 如此公开的礼物礼物;

【讨论】:

  • 这样做了,还是报错。
  • 您是否已将 Present 组件附加到游戏对象并将其附加到检查器中?
  • 是的,做到了。还是有问题。
  • 在上面的代码中,当前字段设置为私有,您是否更改为公共或 [SerializeField] 以便能够附加游戏对象?
  • 是的,我没有在这里编辑脚本。我现在就这样做。
猜你喜欢
  • 2023-04-10
  • 2013-08-09
  • 1970-01-01
  • 1970-01-01
  • 2018-12-10
  • 1970-01-01
  • 2016-05-26
  • 1970-01-01
  • 2012-02-27
相关资源
最近更新 更多