【问题标题】:Unity spawn enemies [duplicate]团结产生敌人[重复]
【发布时间】:2016-06-25 09:20:03
【问题描述】:

目前我的生成系统可以生成简单然后中等的敌人,但是我遇到了 Array out of range 错误,它只生成了 4 个敌人。我想要 x20 简单(或一般数字)x20 中等,然后在(简单、中等和硬敌人之间随机)。

这是我的代码

public GameObject[] enemy; 

public Transform[] spawnPoints;         

private float timer = 2;


int index = 0 ;

int wave = 0;

List <GameObject> EnemiesList = new List<GameObject>();

private int enemyCount=20;


void Update()
{
 timer -= Time.deltaTime;

if (timer <= 0 && wave < 6)
{
    timer = 3;

    if (wave != 0 &&  wave % 2 == 0)
    {
        index ++ ;
    }

    EnemySpawner();

    wave++;
}

}

void Spawn ()
 {
    for (int i = 0; i<enemyCount;i++)
    {
       Invoke("EnemySpawner" , i + 2);
    }
 }

 void EnemySpawner ()
 {
    int spawnPointIndex = Random.Range (0, spawnPoints.Length);

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

EnemiesList.Add(InstanceEnemies);

}

}

【问题讨论】:

    标签: c# unity3d unityscript


    【解决方案1】:

    异常可能来自enemy[index],您的代码使用索引0、1、2。是否有3 个GameObjects 建议给enemy[]?

    spawnPoints[spawnPointIndex] 可能为空,因此 spawnPoints[0] 将导致该异常。 spawnPoints[] 中是否至少有一个变换?

    为防止出现异常,您可以执行以下操作:

    if ( index > 0 && index < enemy.Length && spawnPointIndex > 0 && spawnPointIndex < spawnPoints.Length )
    {
        GameObject InstanceEnemies= Instantiate ( enemy[index] , spawnPoints[spawnPointIndex].position , spawnPoints[spawnPointIndex].rotation) as GameObject;
    
        EnemiesList.Add(InstanceEnemies);
    }
    

    【讨论】:

    • 不,错误来自索引而不是 spawnPointIndex,请问我怎样才能使产卵无休止?谢谢:)
    猜你喜欢
    • 2022-11-01
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多