스파르타 게임개발종합반(Unity)/TIL - 본캠프 매일 공부 기록

2024.08.10 TIL - Update에서 코루틴 호출하기 VS 재귀로 호출하기

테크러너 2024. 8. 10.

Update에서 코루틴 호출하기

    public override void Execute()
    {
        base.Execute();
        fsm.StartCoroutine(DetectClosestTargetCoroutine());
    }

    private IEnumerator DetectClosestTargetCoroutine()
    {
        currentDetectionRadius = fsm.initialDetectionRadius;

        while (fsm.target == null && currentDetectionRadius <= fsm.maxDetectionRadius)
        {
            fsm.target = FindClosestTarget(fsm.EnemyTag, currentDetectionRadius);
            if (fsm.target != null)
            {
                Player.Instance.SetPixelmonsTarget(fsm.target);
                fsm.ChangeState(fsm.MoveState);
                yield break;
            }
            currentDetectionRadius += fsm.radiusIncrement;
            yield return detectionInterval;
        }

        // 최대 탐지 반경까지 찾지 못한 경우, currentDetectionRadius를 초기화
        currentDetectionRadius = fsm.initialDetectionRadius;
    }

한 가지 알아두어야 할 점은 여기에서 Execute()는 Update에서 실행된다.

최대 탐지 반경까지 찾지 못한 경우 Update에 의해 다시 코루틴이 시작된다.

그래서 그냥 코루틴을 한 번 실행하고 최대 탐지 반경까지 찾지 못한 경우에 재귀호출을 하면 되지 않을까? 생각했다.

 

그래서 CPU가 얼마나 튀기는지 실험해봤다.

오른쪽에 빨간원이 탐지 반경이다. 저 탐지가 시작된 시점부터 제일 CPU가 튀겼던 값이 23.3ms였고, 이후에는 5~7ms를 왔다갔다 했다.

 

 

코루틴 재귀 호출

    public override void Enter()
    {
        base.Enter();
        fsm.target = null;
        Player.Instance.SetPixelmonsTarget(null);
        Player.Instance.ChangePixelmonsState(PixelmonState.Idle);
        fsm.joystick.gameObject.SetActive(true);
        fsm.StartCoroutine(DetectClosestTargetCoroutine());
    }

    private IEnumerator DetectClosestTargetCoroutine()
    {       
        currentDetectionRadius = fsm.initialDetectionRadius;      

        while (fsm.target == null && currentDetectionRadius <= fsm.maxDetectionRadius)
        {
            fsm.target = FindClosestTarget(fsm.EnemyTag, currentDetectionRadius);
            if (fsm.target != null)
            {
                Player.Instance.SetPixelmonsTarget(fsm.target);
                fsm.ChangeState(fsm.MoveState);
                yield break;
            }
            currentDetectionRadius += fsm.radiusIncrement;
            yield return detectionInterval;
        }

        // 최대 탐지 반경까지 찾지 못한 경우, currentDetectionRadius를 초기화
        currentDetectionRadius = fsm.initialDetectionRadius;
        fsm.StartCoroutine(DetectClosestTargetCoroutine());
    }

여기에서 Enter는 Fsm 상태 전환시 처음 호출되는 메서드로, 한 번만 호출되는 메서드이다.

최대 탐지 반경까지 찾지 못한 경우 다시 StartCoroutine을 해주고 있다.

재귀 호출을 한 것이다.

 

와우 CPU가 제일 튀겼던 값이 104ms, 106ms이다.

 

심지어 오버플로우도 뜬다..

 

Update에서 호출하는 것이 마냥 안좋다라고만 생각해서 재귀로 바뀌려했는데 더 안좋은 것 같다. 재귀를 사용한다면 오버플로우를 조심하도록 코드를 작성해야할 것 같다.

반응형

댓글