49 lines
1.7 KiB
C#
49 lines
1.7 KiB
C#
using System;
|
|
using UnityEngine;
|
|
using UnityEngine.InputSystem;
|
|
|
|
public class InputManager : MonoBehaviour, GameInput.ICharacterActions
|
|
{
|
|
// 외부에서 InputManager.Instance.OnXxx_Event += handler 형태로 구독.
|
|
public static InputManager Instance { get; private set; }
|
|
|
|
private GameInput _input;
|
|
|
|
public event Action<Vector2> OnMove_Event;
|
|
public event Action OnAttack_Event;
|
|
|
|
private void Awake()
|
|
{
|
|
if (Instance == null)
|
|
{
|
|
Instance = this; //만들어진 자신을 인스턴스로 설정
|
|
DontDestroyOnLoad(gameObject); //씬이 바뀌어도 파괴되지 않도록 설정
|
|
}
|
|
else
|
|
{
|
|
Destroy(gameObject); //이미 인스턴스가 있으면 자신을 파괴
|
|
}
|
|
|
|
_input = new GameInput();
|
|
_input.Character.SetCallbacks(this);
|
|
}
|
|
|
|
// GameInput은 활성/비활성 토글이 필요한 자원 ?. 처리로 Awake보다 OnEnable이 먼저 호출되는 경우 보호.
|
|
private void OnEnable() => _input?.Character.Enable();
|
|
private void OnDisable() => _input?.Character.Disable();
|
|
private void OnDestroy() => _input?.Dispose();
|
|
|
|
public void OnMove(InputAction.CallbackContext ctx)
|
|
{
|
|
// Performed만 받으면 키를 뗐을 때(Canceled) 0이 전달되지 않아 계속 움직인다.
|
|
// Canceled의 ReadValue는 Vector2.zero를 돌려준다.
|
|
if (ctx.phase == InputActionPhase.Performed || ctx.phase == InputActionPhase.Canceled)
|
|
OnMove_Event?.Invoke(ctx.ReadValue<Vector2>());
|
|
}
|
|
|
|
public void OnAttack(InputAction.CallbackContext ctx)
|
|
{
|
|
if (ctx.phase == InputActionPhase.Started)
|
|
OnAttack_Event?.Invoke();
|
|
}
|
|
} |