유니티/코드
Input Action 관리
fore4022
2024. 8. 27. 15:29
input action을 통해서 값을 가져올 곳이 꼭 하나로 특정되는 것이 아니기에, 다른 곳에서도 접근 가능하도록 하고 싶어서 작성하게 되었다.
본인이 이해한 내용을 바탕으로 만들었기에 성능 최적화나, 모든 경우에 대한 오류의 대응이 미흡할 수 있다. 본인도 사용하면서 수정하거나, 조금이라도 더 최적화를 한다면, 여기의 내용도 그때 그때 수정할 것이다.
using System.Collections.Generic;
using UnityEngine.InputSystem;
public static class InputActions
{
public static List<IInputActionCollection> inputActionList = new();
public static T CreateAndGetInputAction<T>() where T : IInputActionCollection, new ()
{
if(GetInputAction<T>(out T inputAction) != null)
{
return inputAction;
}
else
{
T newInputAction = new();
inputActionList.Add(newInputAction);
return newInputAction;
}
}
public static T GetInputAction<T>() where T : IInputActionCollection, new()
{
IInputActionCollection instance = inputActionList.Find(input => input.GetType() == typeof(T));
bool isInclude = instance != null;
if(inputActionList.Count == 0)
{
Managers.Scene.loadScene -= ClearActions;
Managers.Scene.loadScene += ClearActions;
}
if (isInclude)
{
return (T)instance;
}
return default;
}
public static T GetInputAction<T>(out T inputAction) where T : IInputActionCollection, new()
{
inputAction = GetInputAction<T>();
return inputAction;
}
public static void EnableInputAction<T>() where T : IInputActionCollection, new()
{
if(GetInputAction<T>(out T inputAction) != null)
{
inputAction.Enable();
}
}
public static void DisableInputAction<T>() where T : IInputActionCollection, new()
{
if(GetInputAction<T>(out T inputAction) != null)
{
inputAction.Disable();
}
}
public static void ClearActions()
{
inputActionList = new();
Managers.Scene.loadScene -= ClearActions;
}
}
// c# 스크립트화 된 input action의 타입명을 넣어서, 생성된 input action 객체를 가져올 수 있다.
// 생성해서 가져온 input action 객체로 활성화 또는 비활성화 시킬 수 있다.
아직 많이 부족한 코드이니, 틀린 점이나 개선 여지가 있는 것을 지적해주세요.
오늘도 방문해 주셔서 감사합니다.
최근 수정 날짜 : 2024.10.26