@Coroutine

2023-04-10
简介 Overview
.协同程序是一个可以暂停yield执行的函数,直到给定的暂停指令Yield Instruction完成
.和主程序/主进程同步执行,实现等待/延时效果
.使用IEnumerator声明一个协程函数
.使用yield return返回协程结果
.更多使用细节,请查阅API
主要函数
StartCoroutine 开启协程
StopCoroutine 停止协程
WaitForSeconds 等待时间,单位是秒
StopAllCoroutines 停止所有协程
示例 Demo
[] 游戏一开始启动协程,5秒后执行对应代码
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class Demo : MonoBehaviour
    {
        void Start()
        {
            print("app start");
            StartCoroutine(WaitToPrint());
        }

        IEnumerator WaitToPrint()
        {
            yield return new WaitForSeconds(5);
            print("Coroutine:waiting for print");
        }
    }
[] 多波敌人依次出现
代码1:数据文件
    [System.Serializable]
    public class Wave
    {
        public GameObject enemyprefab;
        public int count;
        public float inter;
    }
代码2:主业务逻辑
    public class MonSpawn : MonoBehaviour
    {
        public Wave[] waves;
        public Transform posFre;
        public int waveInter;
        void Start()
        {
            StartCoroutine(MonGer());
        }
        
        IEnumerator MonGer()
        {
            foreach (Wave waveItem in waves)
            {
                for (int i = 0; i < waveItem.count; i++)
                {
                    Instantiate(waveItem.enemyprefab, posFre.position, Quaternion.identity);
                    yield return new WaitForSeconds(waveItem.inter);
                }
                yield return new WaitForSeconds(waveInter);
            }
        }
    }