83 lines
2.9 KiB
C#
83 lines
2.9 KiB
C#
using System.Collections;
|
||
using System.Collections.Generic;
|
||
using Ichni.Menu;
|
||
using TMPro;
|
||
using UnityEngine;
|
||
using UnityEngine.InputSystem;
|
||
using UnityEngine.UI;
|
||
|
||
namespace Ichni.UI
|
||
{
|
||
public class KeyRebindButton : SettingsUIElementBase
|
||
{
|
||
InputActionAsset inputActions => rebindingWindow.inputActions;
|
||
|
||
public RebindingWindow rebindingWindow;
|
||
public Button button;
|
||
public TMP_Text keyText;
|
||
public GameObject waitingForInputCover;
|
||
|
||
public void SetUp(string title, string subtitle, string actionName, int bindingIndex)
|
||
{
|
||
base.SetUp(title, subtitle);
|
||
button.onClick.AddListener(() => StartRebinding(actionName, bindingIndex));
|
||
}
|
||
|
||
// 开始重绑定流程
|
||
public void StartRebinding(string actionName, int bindingIndex)
|
||
{
|
||
// 禁用Action Map以防在重绑定时触发动作
|
||
|
||
inputActions.Disable();
|
||
waitingForInputCover.SetActive(true);
|
||
|
||
var action = inputActions.FindAction(actionName);
|
||
if (action == null)
|
||
{
|
||
Debug.LogError($"在InputActionAsset中未找到名为 '{actionName}' 的Action。");
|
||
return;
|
||
}
|
||
|
||
// 开始交互式重绑定
|
||
rebindingWindow.rebindingOperation = action.PerformInteractiveRebinding(bindingIndex)
|
||
// 可选:排除某些按键,例如不希望鼠标位置被绑定
|
||
.WithControlsExcluding("Mouse")
|
||
.OnMatchWaitForAnother(0.1f)
|
||
// 当重绑定完成时调用
|
||
.OnComplete(operation =>
|
||
{
|
||
operation.Dispose();
|
||
|
||
// 重新启用Action Map
|
||
inputActions.Enable();
|
||
|
||
waitingForInputCover.SetActive(false);
|
||
|
||
// 更新UI显示
|
||
UpdateUIText(actionName, bindingIndex);
|
||
|
||
// 保存新的键位设置
|
||
rebindingWindow.SaveBindings();
|
||
})
|
||
// 当重绑定被取消时(例如按Esc)
|
||
.OnCancel(operation =>
|
||
{
|
||
operation.Dispose();
|
||
inputActions.Enable();
|
||
waitingForInputCover.SetActive(false);
|
||
})
|
||
.Start(); // 启动重绑定操作
|
||
}
|
||
|
||
// 更新单个按钮的UI文本
|
||
public void UpdateUIText(string actionName, int bindingIndex)
|
||
{
|
||
var action = inputActions.FindAction(actionName);
|
||
if (action != null)
|
||
{
|
||
string displayName = action.GetBindingDisplayString(bindingIndex, InputBinding.DisplayStringOptions.DontUseShortDisplayNames);
|
||
keyText.text = displayName.ToUpper();
|
||
}
|
||
}
|
||
}
|
||
} |