美文网首页
2018-02-21 Unity Space Shooter 教

2018-02-21 Unity Space Shooter 教

作者: notAGhost | 来源:发表于2018-02-21 12:20 被阅读0次

概述

  使得小行星(Asteroid)分波到来,一波十个,依次到来。这节视频要点概念是协程(coroutine),这篇文章写的很好,但如果不理解文章里提到的某些概念,理解起来可能有些困难,可以先尝试着看看yieldIEnumerator

协程的效果

  unity里,我们用协程是在用它的这样一个能力:可以暂停一段代码的执行,在下一帧或一段时间后继续执行之前被暂停执行的代码。

代码分析

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

public class GameController : MonoBehaviour {
    public GameObject hazard;
    public Vector3 spawnValue;
    public int hazardCount;
    public float spawnWait;
    public float startWait;
    public float waveWait;

    void Start () {
        StartCoroutine( SpawnWaves ());
    }

    IEnumerator SpawnWaves(){
        yield return new WaitForSeconds(startWait);
        while (true)
        {
            for (int i = 0; i < hazardCount; i++)
            {
                Vector3 spawnPosition = new Vector3(Random.Range(-spawnValue.x, spawnValue.x), spawnValue.y, spawnValue.z);
                Quaternion spawnRotation = Quaternion.identity;
                Instantiate(hazard, spawnPosition, spawnRotation);
                yield return new WaitForSeconds(spawnWait);
            }
            yield return new WaitForSeconds(waveWait);
        }
    }

}

  这里需要关注的就三点:

  • 返回值类型IEnumerator
  • yield return
  • StartCoroutine

  SpawnWaves是一个迭代区块,可以通过foreach来使用IEnumerator,具体细节应该是被封装在StartCoroutine中了。
  SapwnWaves方法应该是被多次调用。值得注意的是,每次运行迭代器方法SpawnWaves时,若是遇到了yield return,则返回yield return后面的表达式,并保存好当前运行到的代码位置,下次调用SpawnWaves方法时则从保存的位置开始运行。
  yield return返回的值可以没有意义,这里的new WaitForSeconds重点在于实现时延,而非用其值。此时主程序没有被暂停,该协程暂停运行了,并在时延结束时恢复运行。WaitForSeconds官方文档详细介绍了这个方法。
  最终的奥妙应该是藏在StartCoroutine中,但这是Unity自带的函数,无法查看。

最后

  之前没有接触过相关东西,花了点时间研究了一下,大概只懂了点皮毛。一点点进步吧。

相关文章

网友评论

      本文标题:2018-02-21 Unity Space Shooter 教

      本文链接:https://www.haomeiwen.com/subject/hbontftx.html