"인간이 있는 한 전쟁이 있을 것이다." – Albert Einstein

2021/05/30

코루틴 동작여부 확인하는 방법

단순히 코루틴을 시작하거나 현재 동작 여부 상관없이 멈추는 경우에는 제공하는 함수를 사용하면 되지만, 코루틴이 현재 돌아가고 있는지 확인해야 하는 경우에는 StartCoroutine 반환 값으로 나온 Coroutine을 받아서 이 값이 null인지 확인하는 방법을 저도 그랬었고 다른 곳 글을 읽어보다 보면 많이들 그렇게 하시던데 사실 코루틴은 동작이 완전히 끝나더라도 시작 시 받아놓은 값은 null이 되지 않아서 이것으로는 코루틴이 현재 돌고 있는지 아닌지 확인할 수가 없습니다.

그리고 유니티에서는 코루틴 동작 상태를 확인하는 변수나 함수를 따로 제공하지 않는 것으로 알고 있습니다. 그래서 보통은 bool 값을 하나 만들어 직접 해당 코루틴 상단에서 true를 넣고, 하단에서 false를 넣어서 밖에서는 이 값을 보고 동작 여부를 파악하는 방식을 사용합니다. 다른 방법도 있겠지만 이 방법이 가장 간단합니다.

private Coroutine[] _coroutines = null;
private bool[] _isDones = null;

void Start()
{
    _coroutines = new Coroutine[ 2 ];
    _isDones = new bool[ 2 ];

    _coroutines[ 0 ] = StartCoroutine( nameof( CoroutineCount ), 0 );
    _coroutines[ 1 ] = StartCoroutine( CoroutineCount( 1 ) );

    StartCoroutine( nameof( CoroutineCheckNull ), 0 );
    StartCoroutine( nameof( CoroutineCheckNull ), 1 );

    StartCoroutine( nameof( CoroutineCheckBool ), 0 );
    StartCoroutine( nameof( CoroutineCheckBool ), 1 );
}

private IEnumerator CoroutineCount( int index )
{
    _isDones[ index ] = true;

    int count = 0;

    while ( count < 3 ) {
        count += 1;

        yield return new WaitForSeconds( 1.0f );
    }

    print( $"done {index}" );

    _isDones[ index ] = false;
}

private IEnumerator CoroutineCheckNull( int index )
{
    while ( null != _coroutines[ index ] ) { // null이 되지 않아서 무한 루프
        yield return null;
    }

    print( $"check null {index}" );
}

private IEnumerator CoroutineCheckBool( int index )
{
    while ( _isDones[ index ] ) {
        yield return null;
    }

    print( $"check bool {index}" );
}

댓글 남기기 | cat > 타닥타닥 | tag >

댓글 남기기

* 표시된 곳은 반드시 입력해주세요