【问题标题】:Unity: NullReferenceException: Object reference not set to an instance of an object with multiple gameObject.SetActive statementsUnity:NullReferenceException:对象引用未设置为具有多个 gameObject.SetActive 语句的对象实例
【发布时间】:2019-01-29 04:47:18
【问题描述】:

我在尝试隐藏作为面板的游戏对象时遇到了该错误。该面板包含一个画布和两个按钮。

最初,面板是隐藏的,脚本可以运行。当我尝试再次启用 panel.SetActive(true) 并返回到 panel.SetActive(false) 时出现错误。

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

public class EquipmentSlot : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerDownHandler, IPointerUpHandler
{
    public GameObject panel;

    void Start()
    {
       GameObject panel= GameObject.FindGameObjectWithTag("panel");
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        GameObject panel= GameObject.FindGameObjectWithTag("panel");
        panel.SetActive(false);
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        GameObject panel = GameObject.FindGameObjectWithTag("panel");
        panel.SetActive(true);
    }
}

我删除了所有不必要的代码。我希望面板在悬停在菜单项上时打开和关闭,您知道,悬停功能在我的代码中有效。

【问题讨论】:

    标签: unity3d gameobject


    【解决方案1】:

    问题

    FindGameObjectWithTag which afaik 等于 GameObject.FindWithTag 在较新版本中找不到不活动的对象!

    返回一个 active GameObject 标记标签。如果没有找到GameObject,则返回null

    因此,在将其设置为 SetActive(false) 后,您将不会再使用任何 Find 变体找到它。

    此外,每次隐藏已经存在的 panel 而不是使用已有的 panel 时,您都会创建一个名为 panel 的新局部变量。

    解决方案

    所以改为在对象处于活动状态时获取引用,并且只获取一次并在以后重新使用它:

    public class EquipmentSlot : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler/*, IPointerDownHandler, IPointerUpHandler*/
    {
        // if you referenced this in the Inspector e.g. via drag & drop
        // you could completely skip the Find in the start method
        public GameObject panel;
    
        void Start()
        {
           panel = GameObject.FindGameObjectWithTag("panel");
        }
    
        public void OnPointerEnter(PointerEventData eventData)
        {
            panel.SetActive(false);
        }
    
        public void OnPointerExit(PointerEventData eventData)
        {
            panel.SetActive(true);
        }
    }
    

    (当然,如果对象同时被销毁,这无论如何都会给你一个例外。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多