導入
変更中はアクションを無効にし、完了・キャンセルの両方でRebindingOperationをDisposeします。元の有効状態へ戻し、Binding OverrideのJSONを保存します。
準備と配置
Input Systemを導入し、JumpアクションにSpaceの単独Bindingを作ります。jump InputActionReferenceとbindingLabel TMP_TextをRebindButtonへ登録し、RebindをButtonへ接続します。
Unity 6向けの例です。[SerializeField]を付けた参照や設定値をInspectorで登録します。文字の参照には対応するTextMeshProコンポーネントを割り当てます。Canvas内の文字はUI > Text - TextMeshProで作れます。
新Input SystemでUI Buttonを操作する場合は、EventSystemにInputSystemUIInputModuleを設定します。旧Standalone Input Moduleを使う場合はActive Input HandlingをBothにして、入力方式をそろえます。
処理の流れ
- 変更中: 入力を無効化
- 新しいキーを取得
- 保存して入力を再開
完成版
以下は記事内の最小例です。機能の範囲は後述の「この例の範囲」で確認してください。
RebindButton.cs
using UnityEngine;
using UnityEngine.InputSystem;
using TMPro;
public class RebindButton : MonoBehaviour
{
[SerializeField]
InputActionReference jump;
[SerializeField]
TMP_Text bindingLabel;
InputActionRebindingExtensions.RebindingOperation operation;
bool wasEnabled;
void Start()
{
string json = PlayerPrefs.GetString("jumpBindings", "");
if (!string.IsNullOrEmpty(json))
jump.action.LoadBindingOverridesFromJson(json);
Refresh();
}
public void Rebind()
{
if (operation != null)
return;
wasEnabled = jump.action.enabled;
jump.action.Disable();
bindingLabel.text = "新しいキーを押してください / Escapeで中止";
operation = jump.action.PerformInteractiveRebinding(0).WithCancelingThrough("<Keyboard>/escape").OnCancel(Finish).OnComplete(Finish).Start();
}
void Finish(InputActionRebindingExtensions.RebindingOperation op)
{
bool cancelled = op.canceled;
op.Dispose();
operation = null;
if (!cancelled)
{
PlayerPrefs.SetString("jumpBindings", jump.action.SaveBindingOverridesAsJson());
PlayerPrefs.Save();
}
if (wasEnabled)
jump.action.Enable();
Refresh();
}
void Refresh()
{
bindingLabel.text = jump.action.GetBindingDisplayString(0);
}
void OnDisable()
{
if (operation != null)
operation.Cancel();
}
}
Inspectorと呼び出しの接続
登録する参照・設定値: jump、bindingLabel。
検証用Buttonを作る場合は、On Click()の+からスクリプトを付けたGameObjectを登録し、Rebind()を選びます。引数がある関数は、各Buttonに渡す値も設定します。コード側でonClickへ登録する例では、Inspectorへ同じ処理を重ねて登録しません。
動作確認
新しいキーに変えると表示が更新され、再起動後も残ります。Escapeで中止すると元へ戻ります。
この例の範囲
複合Bindingや同じキーの重複検出は別途対応します。実ゲームのジャンプ処理がこのInputActionを使う必要があります。
まとめ
変更中はアクションを無効にし、完了・キャンセルの両方でRebindingOperationをDisposeします。元の有効状態へ戻し、Binding OverrideのJSONを保存します。
この記事のまとめ
キー変更、長押し切替、感度、字幕などを最初から整理して、遊びやすさを落とさない実装方針をまとめます。
