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

2024.06.26 TIL - 아이템 오브젝트가 SetActive(false)일 때 코루틴 사용

테크러너 2024. 6. 27.

아이템 오브젝트가 SetActive(false)일 때 코루틴 사용

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Slower : ItemPickUp
{
    public float ReduceSpeed = 0.1f; 
    public float Duration = 5.0f; // 슬로우 효과 지속 시간

    public override void PickUp(Collider2D collision)
    {
        StatHandler stat = collision.gameObject.GetComponent<StatHandler>();
        CoroutineRunner.Instance.RunCoroutine(ApplySlowEffect(stat));
    }

    private IEnumerator ApplySlowEffect(StatHandler stat)
    {
        var statData = new CharacterStatSO { Type = StatType.Multiple, Condition = new StatData {MoveSpeed = ReduceSpeed } };
        stat.AddStat(statData);
        stat.UpdateStat();

        yield return new WaitForSeconds(Duration);

        stat.RemoveStat(statData);
        stat.UpdateStat();
    }
}

오브젝트가 파괴되거나 `SetActive(false)`상태이면 코루틴이 당연히 실행되지 않는다.

이번 프로젝트에서 아이템을 플레이어가 주우면 아이템이 `SetActive(false)`상태가 되었기에 코루틴 실행을 못하는 현상을 겪었다.

 

 

코루틴 대신 실행해주는 스크립트 작성

using System.Collections;
using UnityEngine;

public class CoroutineRunner : Singleton<CoroutineRunner>
{
    public void RunCoroutine(IEnumerator coroutine)
    {
        StartCoroutine(coroutine);
    }
}

그래서 위와 같이 코루틴을 대신 실행해주는 스크립트를 작성하여 문제를 해결했다.

반응형

댓글