今回はUnityのスクリプトで繰り返し処理を行う「InvokeRepeating」のメモです。
はじめに
Unityのバージョンは2021.3.14f1です。
同じ処理を定期的に繰り返し実行する方法はいくつかありますが、今回は「InvokeRepeating」を利用して実装してみます。
実装開始
まずは「2DObject」→「Sprites」→「Square」を追加します。

Squareに「Rigidbody2D」をアタッチし、BodyTypeをKinematicに変更します。

下記のスクリプトを作成します。
using UnityEngine; public class movePos : MonoBehaviour { private Rigidbody2D _rb; private float Xpos = 0f; void Start() { _rb = GetComponent<Rigidbody2D>(); movePosition(); } private void movePosition() { if (Xpos <= 8.0f) { Xpos += 0.02f; _rb.MovePosition(new Vector2(Xpos,0)); Invoke("movePosition", 0.01f); } } }
Squareオブジェクトにスクリプトを追加して実行すると、下記の様に動きます。指定した位置までmovePositionで何度も実行して動かしています(再帰処理)。

同じ処理をInvokeRepeatingを使うと下記の様な感じに。
using UnityEngine; public class movePos : MonoBehaviour { private Rigidbody2D _rb; private float Xpos = 0f; void Start() { _rb = GetComponent<Rigidbody2D>(); InvokeRepeating("movePosition", 0f, 0.01f); } private void movePosition() { if (Xpos <= 8.0f) { Xpos += 0.02f; _rb.MovePosition(new Vector2(Xpos,0)); } } }
公式リファレンスは下記。0.01秒ごとにmovePositionを実行しています。
一定周期で生成
Squareをプレハブ化して、ヒエラルキーメニューから削除します。

CreateEmptyで空オブジェクトを追加し、CreateSquareとします。

下記スクリプトを作成します。一定周期で生成します。
using UnityEngine; public class CreateSquare : MonoBehaviour { [SerializeField] private GameObject _SquarePrefab; [SerializeField] private float _interval; void Start() { InvokeRepeating("SquareIns", 0f, _interval); } private void SquareIns() { Instantiate(_SquarePrefab); } }
スクリプトを追加して、下記の様にパラメータをセットします。

実行すると下記の様な感じに2秒ごとに生成します。

Update関数で時間を計りながら生成するよりすっきりする感じですね。定期的に出てくる敵とかに使える感じです。止める時はCancelInvokeで止めることが出来ます。
CancelInvoke("SquareIns");