8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Unityゲーム開発】「コルーチン」の導入と使いどころ

Posted at

#解説動画
https://youtu.be/l3C_0ZqAW7c

#コード

Sample.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Sample : MonoBehaviour
{
    // コルーチン:処理を待機させるためのもの
    // 使い方:
    // ・関数の返り値をIEnumeratorにする
    // ・yield return XX; XXの間、待機
    // ・関数の実行にはStartCoroutine(関数);

    // おすすめコルーチン
    // 1.trueになるまで待機する:yield return new WaitUntil
    // ・Inputとの組み合わせで入力まちができる
    // 2.別のコルーチンが終了するまで待機すく: yield return 関数名

    bool isGameOver;
    void Start()
    {
        isGameOver = false;
        // DummyBattle();
        StartCoroutine(Battle());
    }

    IEnumerator Battle()
    {
        Debug.Log("バトル開始");
        while(isGameOver == false)
        {
            yield return PlayerTurn();
            yield return EnemyTurn();
        }
        Debug.Log("バトル終了");
    }


    IEnumerator PlayerTurn()
    {
        yield return new WaitForSeconds(1f);
        Debug.Log("Playerの攻撃");
        yield return new WaitUntil(() => Input.GetKeyDown(KeyCode.Space));
    }

    IEnumerator EnemyTurn()
    {
        yield return new WaitForSeconds(1f);
        Debug.Log("敵の攻撃");
        yield return new WaitForSeconds(1f);
    }


    /*
    void DummyBattle()
    {
        Debug.Log("バトル開始");
        Invoke("PlayerAttack", 1f);
        Debug.Log("敵の攻撃");
        Debug.Log("バトル終了");
    }
    void PlayerAttack()
    {
        Debug.Log("Playerの攻撃");
        Invoke("EnemyAttack", 1f);
    }
    void EnemyAttack()
    {
        Debug.Log("敵の攻撃");
    }
        IEnumerator Battle()
    {
        Debug.Log("バトル開始");
        yield return new WaitForSeconds(1f);
        Debug.Log("Playerの攻撃");
        yield return new WaitUntil( () => Input.GetKeyDown(KeyCode.Space));
        yield return new WaitForSeconds(1f);
        yield return EnemyTurn();
        Debug.Log("バトル終了");
    }

    */

}

#スタジオしまづから
・スタジオしまづでゲームの作り方を学びたい人向けのサロン▶︎https://camp-fire.jp/projects/view/149191
・スタジオしまづ ▶︎ https://fromalgorithm.jimdo.com

8
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?