【问题标题】:Why I'm getting exception that the object PlayConversations destroyed but I'm trying to access it?为什么我得到对象 PlayConversations 被破坏但我试图访问它的异常?
【发布时间】:2020-02-09 22:50:50
【问题描述】:

不是什么异常,而是为什么我得到它?

MissingReferenceException:“PlayConversations”类型的对象已被销毁,但您仍在尝试访问它。 您的脚本应该检查它是否为空,或者您不应该销毁该对象。

这是运行游戏前的截图。脚本 PlayConversations 仅附加到对象对话触发器:

在游戏中运行游戏后,它尝试使用 PlayConversations 脚本,但我遇到了异常。而且我看了很多次,我找不到任何被破坏的对象,或者 PlayConversations 没有附加、被破坏或丢失。

这是游戏运行后的屏幕截图,它正在创建玩家的克隆,我仍然可以看到 PlayConversations 脚本:

这是脚本:

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

public class PlayConversations : MonoBehaviour
{
    private static ConversationTrigger conversationTrigger;
    private static PlayConversations instance;

    private void Awake()
    {
        conversationTrigger = GetComponent<ConversationTrigger>();
        instance = this;
    }

    public static void AddConversationToPlay(int index)
    {
        ConversationTrigger.conversationsToPlay.Add(index);
    }

    public static void PlayMultipleConversations()
    {
        instance.StartCoroutine(conversationTrigger.PlayConversations());
    }

    public static void PlaySingleConversation(int ConversationIndex)
    {
        instance.StartCoroutine(conversationTrigger.PlayConversation(ConversationIndex));
    }  
}

异常发生就行了:

instance.StartCoroutine(conversationTrigger.PlayConversation(ConversationIndex));

似乎实例为空。

【问题讨论】:

  • 如果instance 不为空,您应该在 Awake 上抛出异常,因为您的设计只允许一个实例。也就是说,您可能不应该创建这样的静态类......您可以通过拥有多个实例来了解这可能会出错。这个类的。看看this answer,想想你的类是否真的应该是静态的。将日志添加到 OnDestroy(),以便您可以调试您的实例为何会为空。
  • 另外,你不应该为你的类命名 PlayConversations,类名应该是名词,而不是动作/动词,所以 ConversationPlayer,就像你对触发器所做的那样:)

标签: c# unity3d


【解决方案1】:

看起来您正在为您在 Awake 上为实例设置的 conversationTrigger 使用静态变量。

您是否有可能在游戏中有此组件的多个实例,而 Awake 将 null 分配给不同实例中的变量。

我建议在您的 Awake 呼叫中添加一些日志记录,并在那里的作业中记录一些信息。如果这是问题所在,您应该能够单击日志并跳转到场景中的对象。

【讨论】:

    猜你喜欢
    • 2020-08-19
    • 2021-11-08
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 2016-01-10
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多