개발일지/최종프로젝트
241218(수) [Prefab 동적생성하기]
게임 프로그래머
2024. 12. 18. 21:08
ESC 키를 누를시 설정창이 나오는 UIPausePopup 창
그러나 해당 오브젝트가 Hierachy에 없으면 ESC UI를 활성화 할 수 없다.
(즉, 끄고 켤 수 없다.)
그래서 우선 플레이어에서 Resources.Load를 통해 동적 생성하는 방식으로 가져가기로 했다.
public UIPausePopup currentPausePopup;
private const string filePath = "Prefabs/UI/Popup/UIPausePopup";
public void EscPopupInput()
{
if (currentPausePopup == null)
{
UIPausePopup prefab = Resources.Load<UIPausePopup>(filePath);
currentPausePopup = Instantiate(prefab);
}
else
{
Destroy(currentPausePopup.gameObject);
currentPausePopup = null;
}
}
UIPausePopup을 참조해서
null이면 Resources.Load를 통해 프리팹을 로드해주고
이것을 Instantiate해서 currentPausePopup에 저장해준다.
Instantiate 한다고 자동으로 저장되지 않고 저장할 위치를 명확하게 지정해야 한다.
그리고 Instantiate(prefab)과 currentPausePopup 타입은 같아야된다. ★ 중요 ★
만약 null이 아닐경우 해당 게임오브젝트를 파괴해서(On / Off) 기능이 되도록 한다.
ESC 기능을 인풋시스템에서 추가해주고(button 타입)
BaseState.cs
protected virtual void AddInputActionsCallback()
{
PlayerController input = stateMachine.Player.input;
...중략
input.playerActions.ESC.started += OnEscStarted;
}
protected virtual void RemoveInputActionsCallback()
{
PlayerController input = stateMachine.Player.input;
... 중략
input.playerActions.ESC.canceled -= OnEscCanceld;
}
private void OnEscStarted(InputAction.CallbackContext context)
{
stateMachine.Player.EscPopupInput();
}
상태패턴 기본이 되는 baseState에서 이벤트를 등록해주고 EscPopupInput 메서드를 호출하면 끝