Unity无法识别按下的是哪个按钮

Unity can't identify which button is beeing pressed

我一直在尝试让我的游戏中的选项通过键盘输入来选择。我可以突出显示它们,但我不知道如何让 Unity 识别正在按下哪个按钮以执行特定操作,它在代码的第 28 行中为我提供了 NullReferenceException。有问题的脚本是 BattleSystem 脚本,它附加到事件系统,battleFirstButton 是战斗按钮,enterKey 是“Z”。

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

public class BattleSystem : MonoBehaviour
{
    public GameObject battleFirstButton;

    public KeyCode enterKey;
    Button selectedButton;

    // Start is called before the first frame update
    void Start()
    {
        EventSystem.current.SetSelectedGameObject(null);
        EventSystem.current.SetSelectedGameObject(battleFirstButton);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(enterKey))
        {
            selectedButton.onClick.Invoke();
        }  
    }

    public void SetSelectedButton()
    {
        selectedButton = GetComponent<Button>();
    }

    public void Fight()
    {
        print("Fight option submitted");
    }

    public void Act()
    {
        print("Act option submitted");
    }

    public void Item()
    {
        print("Item option submitted");
    }

    public void Mercy()
    {
        print("Get dunked o-, I mean, Mercy option selected");
    }
}

selectedButton 是一个私有变量,可能永远不会设置任何值,因此它为空。在您访问它之前,请确保它已设置为某些内容。

可能对您的设置方式最简单的修复是:

void Update()
{
    if (Input.GetKeyDown(enterKey))
    {
      // Gets the focused button
      selectedButton = EventSystem.current.currentSelectedGameObject.GetComponent<Button>();
      if (selectedButton != null) 
      {
          selectedButton.onClick.Invoke();
      }
}