[Unity] Invoke, Coroutine 안될 때

박민주·2021년 9월 7일
0

Unity

목록 보기
2/40
post-thumbnail

Invoke나 Coroutine은 많이 사용하는데,
미처 생각하지 못한 부분이 있어 기록해본다

Invoke Scripting API
https://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html

  • 아래의 샘플 스크립트에서 알 수 있듯이 Invoke는 몇 초 뒤에 어떠한 일을 실행시킬 때 사용한다

나의 경우,

  • 총알 같이 발사 후 몇 초뒤에 사라져야 할 오브젝트에 자주 사용한 기억이 있다.
  • 혹은 지금 당장은 바꾸면 안되고, 몇 초 후에 변경되어야 할 bool값을
    다시 초기화 시킬 때 사용하였다.
using UnityEngine;
using System.Collections.Generic;

public class ExampleScript : MonoBehaviour
{
    // Launches a projectile in 2 seconds

    Rigidbody projectile;

    void Start()
    {
        Invoke("LaunchProjectile", 2.0f);
    }

    void LaunchProjectile()
    {
        Rigidbody instance = Instantiate(projectile);
        instance.velocity = Random.insideUnitSphere * 5.0f;
    }
}

Coroutine Scripting API
https://docs.unity3d.com/ScriptReference/Coroutine.html
코루틴도 Invoke와 비슷한 활용도를 가진다고 생각한다.
몇 초 뒤에 무엇인가를 실행시켜야 할 때 자주 사용하였다.

하지만 코루틴이 Invoke보다 더 활용도가 높다고 생각한다.
Coroutine Function 내에서 yield return new waitForSeconds(time)을
여러 번 적절한 타이밍에 호출하면
Screen Fade Effect나 Camera Shake등 디테일한 연출도 할 수 있다.

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    IEnumerator WaitAndPrint()
    {
        // suspend execution for 5 seconds
        yield return new WaitForSeconds(5);
        print("WaitAndPrint " + Time.time);
    }

    IEnumerator Start()
    {
        print("Starting " + Time.time);

        // Start function WaitAndPrint as a coroutine
        yield return StartCoroutine("WaitAndPrint");
        print("Done " + Time.time);
    }
}

이러한 Invoke와 Coroutine은
Time.timeScale = 0 으로 설정되어 있을 때 동작하지 않는다.

이 점을 간과하고 대체 왜 Invoke와 Coroutine이 실행되지 않는거지?
하면서 바보같이 조금 헤맸다.

Invoke는 timescale이 0일 때는 사용할 수 없는 것 같고
Coroutine은
yield return new WaitForSeconds() 대신에
yield return new WaitForSecondsRealtime()을 사용하면 된다!

Coroutine이 활용도가 높지만 간단한 기능에서는
Invoke도 적절하게 사용하면 좋은 것 같다.

profile
Game Programmer

0개의 댓글