今回はUnity2Dで「ランダムな敵」を「ランダムな位置」に生成してみます。
はじめに
Unityのバージョンは2021.3.14f1です。
複数いる敵をランダムに選択し、ランダムな位置に生成してみます。敵キャラだけでなくアイテムなどにも使えそうな感じです。
実装開始
簡単な敵キャラを複数作成し、スクリプトで実装していきます。
敵キャラの作成
Hierarchyで右クリック、「2DObject」→「Sprites」→「Square」を選択。

名前をEnemy_Redに変更、Scaleを変更してColorを赤に変更。

Assetsフォルダ内にドラッグアンドドロップし、プレハブ化します。

同じように、青色と黄色も作成。3種類の敵とします。

スクリプトの作成
下記スクリプトを作成。Startでランダムな位置を生成、SpawnEnemyでランダムに敵を選び生成します。
using UnityEngine; public class Spawner : MonoBehaviour { [SerializeField] private GameObject[] enemyPrefabs; private void Start() { Vector2 position = new Vector2(Random.Range(-5f, 5f), Random.Range(-5f, 5f)); SpawnEnemy(position); } private void SpawnEnemy(Vector3 position) { GameObject enemy = enemyPrefabs[Random.Range(0, enemyPrefabs.Length)]; Instantiate(enemy, position, Quaternion.identity, transform); } }
CreateEmptyで空オブジェクトを追加、名前をSpawnerにしておきます。

スクリプトをアタッチして、Enemyをセットします。

修正
位置を修正して画面内に指定します。
Spawnerの配下に空オブジェクトを追加して、位置を下記の様にセットします。

下記のようにスクリプトを修正、下記では画面内に100体の敵キャラを生成。
using System.Collections; using UnityEngine; public class Spawner : MonoBehaviour { [SerializeField] private GameObject[] enemyPrefabs; [SerializeField] private Transform LeftTop; [SerializeField] private Transform RightBottom; private float minX, maxX, minY, maxY; private void Start() { minX = LeftTop.position.x; maxX = RightBottom.position.x; minY = RightBottom.position.y; maxY = LeftTop.position.y; StartCoroutine(SpawnEnemy()); } private IEnumerator SpawnEnemy() { for (int i = 0; i < 100; i++) { Vector2 position = new Vector2(Random.Range(minX, maxX), Random.Range(minY, maxY)); GameObject enemy = enemyPrefabs[Random.Range(0, enemyPrefabs.Length)]; Instantiate(enemy, position, Quaternion.identity, transform); yield return new WaitForSeconds(1.0f); } } }
パラメータをセットします。

実行すると下記のように。

実際には敵キャラの生成タイミングやDestoryで破棄するなどが必要になりますね。