728x90
반응형
이번 포스트에서는 Unity의 PlayerInput 컴포넌트를 사용하여
Input System을 사용하는 4가지 방법 중에서 4번째인 Invoke C# Events를 알아보겠습니다.
이전의 포스트와 동일하게 옵션을 Invoke C# Events로 변경하도록 하겠습니다.
변경하면 설정 창이 다음과 같이 변경되는 것을 볼 수 있습니다.
Invoke C# Event와 Invoke Unity Event 방식의 가장 큰 차이점은 입력을 통해 호출하는 콜백 함수를
C# 스크립트에서 연결하느냐 유니티 에디터에서 연결하느냐입니다.
이제 Invoke C# Event의 사용 방법을 예제를 통해 알아보겠습니다.
1) Invoke C# Events 사용예제
public class InvokeCSharpEvents : MonoBehaviour
{
// Player Input 컴포넌트
private PlayerInput playerInput;
// 수행할 Input Action들
private InputAction moveHorizontalAction;
private InputAction pressAction;
// 현재 설정된 Action Asset에서 사용할 Action Map
private InputActionMap inGround;
[SerializeField]
private float speed;
private Rigidbody2D rigidbody2D;
private Vector2 direction;
// Awake에서는 PlayerInput과 컴포넌트와 RigidBody2D 컴포넌트를 가져온다
private void Awake()
{
playerInput = GetComponent<PlayerInput>();
rigidbody2D = GetComponent<Rigidbody2D>();
}
private void OnEnable()
{
// 사용중인 Action Asset에서 사용할 Action Map을 가져온다
inGround = playerInput.actions.FindActionMap("InGround");
// 입력 시에 호출할 콜백 함수를 가져오는데 가져오는 방식은 2가지가 존재한다
moveHorizontalAction = inGround.FindAction("MoveHorizontal");
pressAction = inGround["Press"];
pressAction.performed += Press;
// 최종적으로 Action Map을 활성화한다
inGround.Enable();
}
private void OnDisable()
{
// Action Map을 비활성화한다
inGround.Disable();
pressAction.performed -= Press;
}
private void FixedUpdate()
{
rigidbody2D.velocity = new Vector2(direction.x * speed, rigidbody2D.velocity.y);
}
private void Update()
{
direction.x = moveHorizontalAction.ReadValue<float>();
}
private void Press(InputAction.CallbackContext value)
{
Debug.Log("Press");
}
}
기존에 사용하던 Invoke Unity Events 방식과 비교하면 다음의 과정으로 처리하는 것을 볼 수 있습니다.
- 우선, PlayerInput 컴포넌트를 가져와서
- 사용할 Action Map을 선택하고
- Action Map에서 다시 사용할 Input Action을 가져온다
최종적으로 실행 결과를 확인해보겠습니다.
기존의 Invoke C# Events 방식처럼 문제없이 실행되는 것을 볼 수 있습니다.
728x90
반응형
'유니티 > 유니티 C#' 카테고리의 다른 글
유니티 입력 처리 심화 - (13) Action Asset에서의 Index와 Composite (0) | 2025.01.23 |
---|---|
유니티 입력 처리 심화 - (12) UI 입력 (0) | 2025.01.08 |
유니티 입력 처리 심화 - (10) Player Input 컴포넌트 - Invoke Unity Events (0) | 2025.01.04 |
유니티 입력 처리 심화 - (9) Player Input 컴포넌트 - Broadcast Messages (0) | 2025.01.02 |
유니티 입력 처리 심화 - (8) Player Input 컴포넌트 - Send Messages (0) | 2025.01.02 |