Menu
CoddyTech

タイマーで生成

CoddyのUnityジャーニー「Unityスクリプトの基礎」セクションの一部。レッスン 63/85。

数秒ごとに何かを生成するスポナーには、タイマーが必要です。Time.deltaTimeは直前のフレームにかかった時間なので、毎回のUpdate()でその値をフィールドに加算すると、経過した秒数がわかります。合計が間隔に達したら生成し、その合計から間隔を差し引きます。

この噴水は0.5秒ごとに水滴を投げ出します。

public GameObject dropPrefab;
public float interval = 0.5f;
float timer;

void Update()
{
    timer += Time.deltaTime;
    if (timer >= interval)
    {
        Instantiate(dropPrefab, transform.position, Quaternion.identity);
        timer -= interval;
    }
}

timer -= intervalにすると余りが保持されます。フレームが0.51秒で終わった場合、次の0.5秒は0.01秒から数え始めるため、水滴は一定のリズムで落ちます。timer = 0ではその余りが失われるため、水滴が少しずつ遅れていき、長時間プレイすると遅れが積み重なります。インスペクターで設定する必要がないので、timerはprivateです。

challenge icon

チャレンジ

中級

interval秒ごとにボックスを1つ落とします(Inspectorで2に設定)。

  1. float timer;とint count;フィールドを追加します。Update()で、Time.deltaTimeをtimerに加算します。
  2. timer >= intervalのとき、Instantiate(boxPrefab, transform.position, Quaternion.identity);を呼び出し、timerからintervalを引きます。
  3. 次に、countに1を加算し、"Box " + countをログに出力します。

「プレイ」を押すと、2秒ごとにボックスが落ち、ConsoleにBox 1、Box 2と表示されます。その後、「確認」を押します。

自分で試してみよう

using UnityEngine;

public class BoxDropper : MonoBehaviour
{
    public GameObject boxPrefab;
    public float interval = 1f;

    void Update()
    {
        // interval 秒ごとに箱を落とし、"Box 1"、"Box 2"…とログに記録する
    }
}

Unityスクリプトの基礎のすべてのレッスン

自分で練習してみよう: Unityプレイグラウンド