我一直在尝试通过键盘输入来选择我的游戏中的选项。我可以突出显示它们,但我不知道如何让 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");
}
}