Unity/점프 게임

[유니티] 인보크를 코르틴으로 바꾸기

Skull Crusher 2021. 5. 6. 09:28
728x90

 

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

public class ObjectGenerator : MonoBehaviour
{

    public GameObject prefab;
    
    public Transform genPosition;
    
    public float topGenPosY;
    public float bottomGenPosY;

    public float genStartDelayTime;
    public float genDelayTime;

    // Start is called before the first frame update
    void Start()
    {
        //InvokeRepeating("ObjectGenerateTimer", genStartDelayTime, genDelayTime);
        StartCoroutine("ObjectGenerateCoroutine");
    }

    private void Update()
    {
        //게임 끝나면 동작 취소
        if (GameManager.IsGameStop)
        {
            // CancelInvoke("ObjectGenerateTimer");
            StopCoroutine("ObjectGenerateCoroutine");
        }

    }

    //아이템 생성 코루틴
    IEnumerator ObjectGenerateCoroutine()
    {
        //생성을 위한 시작 지연을 수행
        yield return new WaitForSeconds(genStartDelayTime);

        while (true)
        {
            //코루틴을 생성 대기 시간만큼 실행 지연
            yield return new WaitForSeconds(genDelayTime);

            //지정한 아이템을 생성함
            ObjectGenerateTimer();
        }
    }

    void ObjectGenerateTimer()
    {
        float genY = Random.Range(topGenPosY, bottomGenPosY);

        Vector2 pos = new Vector2(genPosition.position.x, genPosition.position.y + genY);

        //prefab 복제
        Instantiate(prefab, pos, Quaternion.identity);
    }
}