0

我一直在尝试通过键盘输入来选择我的游戏中的选项。我可以突出显示它们,但我不知道如何让 Unity 识别正在按下哪些按钮以执行特定操作,它给了NullReferenceException我代码的第 28 行。有问题的脚本是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");
    }
}

在此处输入图像描述

四个按钮的 OnClick() 函数

在此处输入图像描述

4

1 回答 1

2

selectedButton is a private variable potentially never set to anything, so it's null. Make sure it's set to something before you access it.

Probably the simplest fix to the way you have it set up is:

void Update()
{
    if (Input.GetKeyDown(enterKey))
    {
      // Gets the focused button
      selectedButton = EventSystem.current.currentSelectedGameObject.GetComponent<Button>();
      if (selectedButton != null) 
      {
          selectedButton.onClick.Invoke();
      }
}
于 2020-07-19T18:44:00.237 回答