98 lines
3.3 KiB
C#
98 lines
3.3 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;
|
||
|
||
private bool _isClickListenerRegistered;
|
||
|
||
/// <summary>
|
||
/// 初始化重绑定行为。标题和说明由 Prefab 上的 LocalizedTMPText 配置;
|
||
/// <paramref name="actionName"/> 仅用于定位 Input System Action,不是本地化 Key。
|
||
/// </summary>
|
||
public void SetUp(string actionName, int bindingIndex)
|
||
{
|
||
base.SetUp();
|
||
if (_isClickListenerRegistered)
|
||
{
|
||
return;
|
||
}
|
||
|
||
button.onClick.AddListener(() => StartRebinding(actionName, bindingIndex));
|
||
_isClickListenerRegistered = true;
|
||
}
|
||
|
||
// 开始重绑定流程
|
||
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。");
|
||
inputActions.Enable();
|
||
waitingForInputCover.SetActive(false);
|
||
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();
|
||
}
|
||
}
|
||
}
|
||
}
|