(Unity)コルーチン(StartCoroutine/break/引数)

<その1・基本形>

  • スペースキーを押すと開始
  • 1秒ごとにブロックを10個並べる。

(スクリプト)

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

public class CoroutineTest_1 : MonoBehaviour
{
    public GameObject blockPrefab;
    private Vector3 pos;

    private void Start()
    {
        pos = transform.position;
    }

    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            StartCoroutine(BlockGene());
        }
    }

    private IEnumerator BlockGene()
    {
        for(int i = 0; i < 10; i++)
        {
            Instantiate(blockPrefab, new Vector3(pos.x + i, pos.y + i, pos.z), Quaternion.identity);

            yield return new WaitForSeconds(1);
        }
    }
}

(実行結果)


(その2・break)

  • 5個並べた時点で途中終了

(スクリプト)

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

public class CoroutineTest_2 : MonoBehaviour
{
    public GameObject blockPrefab;
    private Vector3 pos;

    private void Start()
    {
        pos = transform.position;
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            StartCoroutine(BlockGene());
        }
    }

    private IEnumerator BlockGene()
    {
        for (int i = 0; i < 10; i++)
        {
            // ★条件成立で終了
            if (i == 5)
            {
                yield break;
            }

            Instantiate(blockPrefab, new Vector3(pos.x + i, pos.y + i, pos.z), Quaternion.identity);

            yield return new WaitForSeconds(1);
        }
    }
}

(実行結果)


(その3・引数)

  • 引数のあるコルーチン
  • 1.5秒ごとにブロックを7個並べる。

(スクリプト)

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

public class CoroutineTest_3 : MonoBehaviour
{
    public GameObject blockPrefab;
    private Vector3 pos;

    private void Start()
    {
        pos = transform.position;
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            StartCoroutine(BlockGene(7, 1.5f));
        }
    }

    // *引数の設定
    private IEnumerator BlockGene(int num, float s)
    {
        for (int i = 0; i < num; i++)
        {
            Instantiate(blockPrefab, new Vector3(pos.x + i, pos.y + i, pos.z), Quaternion.identity);

            yield return new WaitForSeconds(s);
        }
    }
}

(実行結果)