停止允许 random.range 拾取相同的重生点。它会导致敌人相互重叠

Stop allowing random.range to pick up the same spawnpoint. it causes the enemies to overlap over each other

你好,我有一个敌人重生系统,它工作正常。但是敌人在同一点上重叠,因为我使用 random.range,我在地图上有 4 个点,我希望每个敌人随机选择一个点。因此,我希望在生成敌人后,其他敌人只有 3 个生成选项,而不是 4 个。

这是我的代码:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Spawn : MonoBehaviour {

    // The enemy prefab to be spawned.
    public GameObject[] enemy;  

    //public Transform[] spawnPoints;         
    public List<Transform> spawnPoints = new List<Transform>();
    private float timer = 3;

    int index = 0;    
    List <GameObject> EnemiesList = new List<GameObject>();
    private int m_enemyCount = 4;

    // Update is called once per frame
    void Update () {
        if (timer >0)
        {
            timer -= Time.deltaTime;
        }
        if (timer <= 0 )
        {               
            if ( EnemiesList.Count == 0 )
            {
                Spawner();  
                timer = 5;
            }
        }
    }

    void Spawner ()
    {
        // Create an instance of the enemy prefab at the randomly selected spawn point's position.
        //Create the enemies at a random transform 
        for (int i = 0; i<m_enemyCount;i++)
        {
            int spawnPointIndex = Random.Range (0, spawnPoints.Count);
            Transform pos = spawnPoints[spawnPointIndex];

            GameObject InstanceEnemies= Instantiate ( enemy[index] , spawnPoints[spawnPointIndex].position , Quaternion.identity) as GameObject;

            // Create enemies and add them to our list.
            EnemiesList.Add(InstanceEnemies);               
        }
    }

在 for 循环的末尾从列表 spawnPoints 中删除已经取得的生成点,如下所示:

spawnPoints.RemoveAt(spawnPointIndex);

您可能希望在 for 循环之前创建该列表的副本以保持原始列表不变。

处理此问题的一个简单方法是在您的 Spawner() 方法中创建一个本地生成点列表,这样您就可以跟踪您已经使用了哪些生成点。例如:

void Spawner ()
{
    //create a local list of spawn points
    List<Transform> availablePoints = new List<Transform>(spawnPoints);

    // Create an instance of the enemy prefab at the randomly selected spawn point's position.
    //Create the enemies at a random transform 
    for (int i = 0; i<m_enemyCount;i++)
    {
        //use local availableSpawnPoints instead of your global spawnPoints to generate spawn index
        int spawnPointIndex = Random.Range (0, availableSpawnPoints.Count);
        Transform pos = spawnPoints[spawnPointIndex];

        GameObject InstanceEnemies= Instantiate ( enemy[index] , avaialableSpawnPoints[spawnPointIndex].position , Quaternion.identity) as GameObject;

        // Create enemies and add them to our list.
        EnemiesList.Add(InstanceEnemies);

       //remove the used spawnpoint
       availableSpawnPoints.RemoveAt(spawnPointIndex);

    }
}

此解决方案可确保您的全局生成点列表在您下次调用 Spawner() 方法时保持不变。