본문 바로가기

관리 메뉴

[Unity] StartCoroutine에서 람다식 사용하기 본문

프로그래밍/ㄴ기타

[Unity] StartCoroutine에서 람다식 사용하기

최갓 2019. 11. 13. 18:40
반응형

코드 원문 : 

using System;
 using System.Collections;
 using UnityEngine;

public  static  class CoroutineCommon
{
    private  static  readonly MonoBehaviour mMonoBehaviour;
  
    static CoroutineCommon ()
    {
        var gameObject = new GameObject ( "CoroutineCommon" );
        GameObject.DontDestroyOnLoad (gameObject);
        mMonoBehaviour = gameObject.AddComponent <MonoBehaviour> ();
    }

    public  static  void CallWaitForOneFrame (Action act)
    {
        mMonoBehaviour.StartCoroutine (DoCallWaitForOneFrame (act));
    }
        
    public  static  void CallWaitForSeconds ( float seconds, Action act)
    {
        mMonoBehaviour.StartCoroutine (DoCallWaitForSeconds (seconds, act));
    }

    private  static IEnumerator DoCallWaitForOneFrame (Action act)
    {
        yield  return  0 ;
        act ();
    }

    private  static IEnumerator DoCallWaitForSeconds ( float seconds, Action act)
    {
        yield  return  new WaitForSeconds (seconds);
        act ();
    }
}

사용 : 

public  class Character : MonoBehaviour
{
    private  void Attack ()
    {
        // 1 프레임 기다렸다가 공격 
        CoroutineCommon.CallWaitForOneFrame (() => Debug.Log ( "공격" ));

        // 1 초 기다렸다가 공격 
        CoroutineCommon.CallWaitForSeconds ( 1 , () => Debug.Log ( "공격" ));
    }
}

참고 : 

http://baba-s.hatenablog.com/entry/2014/05/07/165344

반응형
Comments