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?

unity エンドレスに敵を沸かせるスクリプト オブジェクトプール使用

Posted at

・変数定義
敵が出現する時間間隔

public float spawnInterval = 2.0f;

敵の出現位置をplayerから何Mかに設定

public float spawnDistance = 30f;

objectpoolの参照 

public ObjectPool enemyPool;

現在アクティブな敵の一覧を管理するキュー

private Queue<GameObject> active = new Queue<GameObject>();

同時に表示できる敵の最大数

public int maxOnScreen = 6;

・start()メソッド
タグが "Player" のオブジェクトを見つけて、Transform を取得
InvokeRepeating() で SpawnEnemy() を1秒後から spawnInterval ごとに呼び出す

player = GameObject.FindWithTag("Player").transform;
InvokeRepeating(nameof(SpawnEnemy), 1f, spawnInterval);

SpawnEnemy() メソッドの流れ
敵の数が上限に達しているか確認
古い敵はキューから取り出し、プールに戻す

if (active.Count >= maxOnScreen)
{
    GameObject oldEnemy = active.Dequeue();
    enemyPool.ReturnToPool(oldEnemy);
}

新しい敵を取得
オブジェクトプールから敵をもってくる

GameObject enemy = enemyPool.GetFromPool();

出現位置の計算
playerから位置を計算して配置

Vector3 spawnPos = player.position + Vector3.right * spawnDistance;
spawnPos.y = player.position.y;

敵の位置をせっとしてアクティブに

enemy.transform.position = spawnPos;
enemy.SetActive(true);

敵を管理キューに追加

active.Enqueue(enemy);
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?