【发布时间】: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