Infinite Instantiation
I am instantiating enemies. My if
-statement should close itself as soon as one appears, but for some reason it repeats itself over a hundred times before stopping.
Just a note about the code, I only have this code on a single game object and don't instantiate in any other scripts, so it isn't the typical issue where clones are creating clones. Additionally, the editor correctly shows the enemyCount
at any given time. Despite the fact that enemyCount
increases above 1, clones are still generated.
I'm quite new to Unity and C#, so I'm not sure if there's something obvious I'm just missing or if there's some complex reasoning behind the issue. If anyone knows what I can do to fix this, please let me know, it would be greatly appreciated :)
void Update ()
{
if( enemyCount<1 )
Invoke("RespawnEnemies", 2);
}
void RespawnEnemies ()
{
enemyCount ++;
int randomEnemy = Random.Range( 0 , enemySpawnPoints.Length-1 );
Instantiate( enemySpawnPoints[randomEnemy] , transform.position , Quaternion.identity );
}
I am instantiating enemies. My if-statement should close itself as soon as one appears, but for some reason it repeats itself over a hundred times before stopping.
It is because your Update
calls Invoke( nameof(RespawnEnemies) , 2 );
for 2 seconds, every frame (dozens if not hundreds of times per second). Calls to Invoke( nameof(RespawnEnemies) , 2 );
stop after 2 seconds, but delayed torrent of RespawnEnemies()
calls just starts and continues for another 2s.
Delete this Update
and replace it with this:
IEnumerator Start ()
{
var wait = new WaitForSeconds(2);
yield return wait;
while( true )
{
if( enemyCount<1 )
{
int randomEnemy = Random.Range( 0 , enemySpawnPoints.Length-1 );
Instantiate( enemySpawnPoints[randomEnemy] , transform.position , Quaternion.identity );
enemyCount ++;
}
yield return wait;
}
}
Answer by TheIrishKraken · May 16 at 05:32 AM
Using Invoke is causing this issue.
Call the method directly instead & you can use a countdown timer to space out the spawning of the enemies so they don't spawn in too quickly.
So if the enemyCount is less then 1 start a timer that counts down from 2 seconds. When the timer reaches 0 then run RespawnEnemies() & reset the timer.
Answer by WizardGoose · May 16 at 06:13 PM
Thanks, I think both of these solutions work great! I hadn't thought of Evoke being the issue, so this was a ton of help :)