Home > Net >  Values gets destroyed in coroutine
Values gets destroyed in coroutine

Time:09-21

I am wondering why a value passed into a coroutine gets overwrittn each time the coroutine runs. The value is "currentAmountOfEnemiesSpawned" which is declare at the top like this private int currentAmountOfEnemiesSpawned;

Is there something specific when using coroutines which deletes the entry?

Thanks!

   private IEnumerator SpawnEnemy(float secondsBetweenSpawns = 1f)
    {
        print($"Enemies to spawn is: {totalAmountOfEnemiesToSpawn}");
        currentAmountOfEnemiesSpawned  = 1;
        if(currentAmountOfEnemiesSpawned >= totalAmountOfEnemiesToSpawn)
        {
            print("stopping respawn");
            StopEnemySpawning();
        }

        isEnemyReadyToSpawn = false;
        Vector2 rndPosWithin = new Vector2(Random.Range(-1f, 1f), Random.Range(-1f, 1f));
        rndPosWithin = transform.TransformPoint(rndPosWithin * .5f);
        var spawedEnemy = Instantiate(enemyToSpawn, rndPosWithin, transform.rotation);
        spawedEnemy.name = enemyToSpawn.name;
        spawedEnemy.transform.parent = enemyParentGameObject.transform;


        yield return new WaitForSeconds(secondsBetweenSpawns);
        isEnemyReadyToSpawn = true;

    }

    public void StartEnemySpawning(int amountOfEnemiesToSpawn)
    {
        isSpawningPaused = false;
        currentAmountOfEnemiesSpawned = 0;
        totalAmountOfEnemiesToSpawn = amountOfEnemiesToSpawn;
        StartCoroutine(SpawnEnemy(1f));
    }

CodePudding user response:

When you say passing, you have a class level scoped variable named currentAmountOfEnemiesSpawned. Its the same reference so setting it from any method in that class will update it for all.

You may want to introduce a for loop up to currentAmountOfEnemiesSpawned that calls SpawnEnemy method without any need for subsequent code to update/set variable value.

CodePudding user response:

Accidentaly passed in a "1" thinking it was the time, but i passed in 1 as amounts of enemies to spawn... silly. Thanks!

  • Related