0
0

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 1 year has passed since last update.

Unity-Coroutineの使う場面の例5選

0
Posted at

UnityでのCoroutineの活用シーン

Coroutine(コルーチン)は、Unityで時間の経過とともに処理を実行する際に便利な仕組みです。一定時間後に処理を実行したり、アニメーションのように徐々に値を変化させたりする場合に活用されます。


1. 一定時間待ってから処理を実行

例: 敵の攻撃後にクールダウンを入れる

IEnumerator AttackCooldown()
{
    canAttack = false;
    yield return new WaitForSeconds(2.0f); // 2秒待つ
    canAttack = true;
}

WaitForSeconds(n) を使うことで、指定した時間が経過するまで処理を待機できます。


2. 徐々に値を変化させる(アニメーション・エフェクト)

例: フェードイン・フェードアウト

IEnumerator FadeOut(CanvasGroup canvasGroup)
{
    while (canvasGroup.alpha > 0)
    {
        canvasGroup.alpha -= Time.deltaTime; // 少しずつ透明にする
        yield return null; // 次のフレームまで待つ
    }
}

🎨 Time.deltaTime を使って、毎フレーム少しずつ値を変化させることができます。


3. 一定間隔で処理を繰り返す

例: 敵が定期的に攻撃する

IEnumerator EnemyAttack()
{
    while (true) // 無限ループ
    {
        Attack(); // 攻撃処理
        yield return new WaitForSeconds(3.0f); // 3秒ごとに攻撃
    }
}

🔄 while(true) を使用すると、特定の間隔で処理を繰り返すことができます。


4. 外部リソースをロードする

例: Webから画像をダウンロード

IEnumerator LoadImage(string url)
{
    UnityWebRequest request = UnityWebRequestTexture.GetTexture(url);
    yield return request.SendWebRequest(); // ダウンロード待機

    if (request.result == UnityWebRequest.Result.Success)
    {
        Texture texture = ((DownloadHandlerTexture)request.downloadHandler).texture;
        myRenderer.material.mainTexture = texture; // 取得した画像を適用
    }
}

🌍 UnityWebRequest を利用することで、非同期でのリソースダウンロードが可能になります。


5. 物理的な動きをゆっくり変化させる

例: ドアをゆっくり開く

IEnumerator OpenDoor()
{
    float elapsedTime = 0f;
    float duration = 2f; // 2秒かけて開く

    while (elapsedTime < duration)
    {
        door.transform.rotation = Quaternion.Lerp(startRotation, endRotation, elapsedTime / duration);
        elapsedTime += Time.deltaTime;
        yield return null; // 次のフレームまで待つ
    }
    door.transform.rotation = endRotation; // 最終位置にセット
}

🚪 Quaternion.Lerp を使用すると、回転を滑らかに補間できます。


まとめ

用途 説明 関数
一定時間後に処理を実行 例: クールダウン WaitForSeconds(n)
徐々に値を変化させる 例: フェードイン・アウト Time.deltaTime
一定間隔で処理を繰り返す 例: 敵の定期攻撃 while(true) + WaitForSeconds(n)
外部リソースをロード 例: 画像ダウンロード UnityWebRequest
物理的な動きを滑らかにする 例: ドアの開閉 Lerp

まとめ

Coroutineを活用すると、フレーム単位や時間単位で処理を柔軟に制御できます。特に、ゲーム内のエフェクトや時間経過を伴う処理に最適です。適切に活用して、スムーズなゲームプレイを実現しましょう!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?