【问题标题】:NullReferenceException: Object reference not set to an instance of an object in unity c# [duplicate]NullReferenceException:对象引用未设置为统一c#中的对象实例[重复]
【发布时间】:2021-11-03 14:40:47
【问题描述】:

我在从接口实现的方法中访问 SerializeField 时遇到问题。

public class UIManager : MonoBehaviour, IGameOver
{
[SerializeField] 
public GameObject gamePlayPanel;
[SerializeField]
public GameObject gameOverPanel;

[Header("Score-board")]
public Text coinScoreText;
public Text diamondScoreText;

private static int coinScore, diamondScore;

public void EndGame(string reason)
{

    Debug.LogError(gamePlayPanel);  // returning NULL
    Debug.Log("Game Over: UI Manager " + reason);

    gamePlayPanel.SetActive(false); 
    gameOverPanel.SetActive(true);


}
}

界面如下图

public interface IGameOver
{
    void EndGame(string reason);
}

有没有其他方法可以访问 EndGame() 方法中的 SerializeField,该方法被 IGameOver 接口覆盖

【问题讨论】:

  • 你可以只检查空值:if (gamePlayPanel != null)
  • 是的,但我需要访问 gamePlayPanel 字段,它在 EndGame() 之外工作。
  • 界面与游戏对象面板无关。
  • @KlausGütter 虽然这可以防止异常本身,但它只是混淆了实际问题,使调试变得更加困难。该异常至少会立即告诉您出了什么问题,而不是根本没有发生任何事情;)

标签: c# unity3d interface observer-pattern


【解决方案1】:

无论接口的实现如何,对象本身及其子对象始终可以随时访问公共/受保护的函数和变量。

因此,在上面的代码中,访问 EndGame() 函数范围内的 SerializeField 实例应该没有问题。

查看下面的两个列表。

首先,确保您已将 Monobehaviour 连接到 Unity Editor 的 Inspector 窗口中的 SerializeField。

其次,确保在执行 EndGame 函数的那一刻,GamePlayPanel 和 gameOverPanel 对象被 OnDestroy 函数销毁。这是一个顺序问题,因此您需要仔细考虑代码的执行顺序。

【讨论】:

    猜你喜欢
    • 2020-11-17
    • 1970-01-01
    • 2014-07-21
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 2016-06-05
    相关资源
    最近更新 更多