首页 > 解决方案 > 如何通过单击访问单例变量而不导致 NullReferenceException

问题描述

这是我发起 E 的单例类

using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{

    static public Player E;
    public float EA = 5;
    public float EG = 0;

    // Start is called before the first frame update
    void Awake()
    {
        if (E == null)
        {
            E = this;
        }
        else
        {
            Debug.LogError("Hero.Awake() - attempted to assign second Hero.S");
        }
    }

    // Update is called once per frame
    void Update()
    {


        if (EG >= 5 && EA >= 0)
        {
            EG = 0;
        }
        if (EA <= 4 && EG > 9)
        {
            EA = 5;
        }

    }
}

现在,当我尝试通过 OnPointerClick() 访问它以尝试在 UseItem() 方法中修改变量 EA 和 EG 时,系统将生成 NullReferenceException。我试过切换执行顺序,但没有奏效。是因为我试图修改它吗?抱歉,我是 Unity 新手,不知道这些事情。

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


public class Slot : MonoBehaviour , IPointerClickHandler

{
    public int ID;
    public string type;
    public string description;
    public bool empty;
    public Texture2D icon;
    // Start is called before the first frame update
    public void OnPointerClick (PointerEventData pointerEventData)
    {
        useItem();
        Debug.Log("clicked" + transform.name);
    }
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
    public void useItem()
    {
        for (int i = 0; i < 10; i++)
        {
            if (transform.name == "slot(" + (i + 1) + ")")
            {
                Player.E.EA = i;
            }
        }
        Debug.Log(Player.E.EA);
    }
}

标签: c#unity3d

解决方案


这看起来更像是一个 Unity/Monobehavior 问题,而不是 C# 问题。唤醒在游戏开始前触发,只有一次。它可以被视为初始化程序。

由于您有一个公共 E,您需要为其提供一个实例:通过在 Unity IDE 界面中添加一个对象(拖放)或通过代码。

您也可以改用标签。在这里您可以找到有关如何执行此操作的更多信息: https ://docs.unity3d.com/ScriptReference/MonoBehaviour.Awake.html


推荐阅读