using UnityEngine;
using UnityEngine.InputSystem;
using System;
public class InputManager : Singleton<InputManager>
{
public PlayerInputActions _input;
public Vector2 MoveInput { get; private set; }
public Vector2 MouseScreenPosition { get; private set; }
public Vector3 MouseWorldPosition { get; private set; }
public event Action OnAttack;
public event Action OnInteract;
/// <summary>
/// 필독! 아이템 사용 시작시 마우스 무브와 클릭에 구독 사용이 끝날때 구독해제하면 됨
/// vector3 매개변수를 받는 void를 구독할것 EnableMouseTracking를 true해준뒤 사용할것
/// </summary>
public event Action<Vector3> OnMouseClick;
public event Action<Vector3> OnMouseMove;
public bool EnableMouseTracking { get; set; } = false;
private Camera _mainCam;
protected override void Awake()
{
base.Awake();
if (_input == null)
_input = new PlayerInputActions(); // 런타임 생성
_mainCam = Camera.main;
_input.PC.Move.performed += ctx => MoveInput = ctx.ReadValue<Vector2>();
_input.PC.Move.canceled += _ => MoveInput = Vector2.zero;//_사용시 매개변수를 사용하지 않는 경우 ctx는 callback 매개변수를 받아야함
_input.PC.Attack.performed += _ => OnAttack?.Invoke();
_input.PC.Interact.performed += _ => OnInteract?.Invoke();
_input.PC.MousePosition.performed += ctx =>
{
if (!EnableMouseTracking) return;
MouseScreenPosition = ctx.ReadValue<Vector2>();
MouseWorldPosition = _mainCam.ScreenToWorldPoint(MouseScreenPosition);
OnMouseMove?.Invoke(MouseWorldPosition);//vector3 매개변수로 받는 메서드로 추가
};
_input.PC.MouseClick.performed += _ =>
{
if (!EnableMouseTracking) return;
OnMouseClick?.Invoke(MouseWorldPosition);//vector3 매개변수로 받는 메서드로 추가
};
}
public PlayerInputActions GetInputSafe()
{
if (_input == null) _input = new PlayerInputActions();
return _input;
}
private void OnEnable() => _input.PC.Enable();
private void OnDisable() => _input.PC.Disable();
}
C#에서 _ 언더스코어의 쓰임새와 의미
오늘은 C# 코드에서 자주 보이는 _의 다양한 쓰임새를 정리해봤다.
단순히 "아무 이름"이 아니라, "의도적으로 무시하는 값"이라는 점에서 의미가 있다.
1. Discard (버리는 변수)
가장 기본적인 쓰임새.
변수로는 존재하지만, 사용할 필요가 없을 때 _로 처리한다.
튜플에서 일부 값 무시
foreach (var (a, b, _) in edges)
{
// 여기서 세 번째 튜플 값은 무시됨
}
→ _는 "이 값은 필요 없음"이라는 의도를 명확히 전달
out 변수 무시
if (int.TryParse("123", out _))
{
// 값은 안 쓰고 성공 여부만 필요할 때
}
2. Switch Expression의 디폴트 패턴
C# 8.0 이후 등장한 switch expression에서 _는 **"기타 모든 경우"**를 나타냄.
string message = input switch
{
"Y" => "Yes",
"N" => "No",
_ => "Unknown", // 그 외의 모든 값
};
3. Pattern Matching에서의 discard
if (obj is MyType _)
{
// 타입만 검사하고 변수로는 안 씀
}
4. lambda나 delegate 파라미터 무시 (중요)
list.ForEach(_ => DoSomething());
파라미터를 받지만 쓰지 않을 때도 _로 표현 가능
5. 기본 변수 이름으로도 사용 가능 (비추)
int _ = 5;
가능하지만 의미상 오해를 줄 수 있기 때문에 권장되지는 않음
대개 discard 목적일 때만 _ 사용
_는 "이 값은 필요 없으니 신경 쓰지 마세요"라는 의도를 담은 버리는 이름 (discard)