본문 바로가기

TIL

[ 24.05.20 ] 내일배움캠프 24일차 TIL - Input Rebinding

[ ps ]

 

[ 백준 / C++ ] 1431 : 시리얼 번호 (tistory.com)

 

[ Unity ]

 

Input System의 장점 중 하나는 키세팅을 변경하는 부분이 자유롭다는 것이다.

정확히는 런타임 도중 마우스 딸깍으로 키세팅을 변경할 수 있다.

spaceAction.ApplyBindingOverride("<Keyboard>/escape");

 

위 코드를 실행하면 spaceAction에 연결된 키가 esc로 변경된다.

단점으로는 해당 액션의 모든 바인딩이 동시에 변경된다.

만약 해당 액션의 특정 바인딩만을 변경하고 싶다면, 바인딩인덱스를 활용하면 된다.

var bindingIndex = spaceAction.GetBindingIndexForControl(Keyboard.current.spaceKey);
spaceAction.ApplyBindingOverride(bindingIndex, "<Keyboard>/escape");

 

마지막으로 위 코드가 적힌 메서드를 인스펙터 창에서 마우스 딸깍으로 실행하고 싶다면,

ContextMenu 속성에 메서드를 추가해주면 된다.

여기서 ContextMenu는 인스펙터 창에서 컴포넌트 옆에 있는 점 3개를 누르면 나오는 메뉴를 말한다.

[ContextMenu("Rebind")] // 점 3개 -> Rebind 딸깍

 

전체적인 코드는 다음과 같다.

public class InputRebinder : MonoBehaviour
{
    public InputActionAsset actionAsset;
    private InputAction spaceAction;

    void Start()
    {
        spaceAction = actionAsset.FindAction("move");

        if (spaceAction == null)
            return;

        spaceAction?.Enable();
    }

    [ContextMenu("Rebind")]
    public void RebindSpaceToEscape()
    {
        if (spaceAction == null)
            return;

	// spaceAction.ApplyBindingOverride("<Keyboard>/escape");
        var bindingIndex = spaceAction.GetBindingIndexForControl(Keyboard.current.spaceKey);
        spaceAction.ApplyBindingOverride(bindingIndex, "<Keyboard>/escape");
    }

    void OnDestroy()
    {
        spaceAction?.Disable();
    }
}