Robert Butchers
Robert Butchers

Reputation: 11

Working in unity, Variable changed via a function immediately resets to previous value

I have 3 Scripts working within unity

Script A (SpawnManager)

Has a Bool called spawnenemy and at the start is set to true. IENumerator is running to spawn an enemy every couple of seconds.

Script B

Keeps track of score. When score reaches a target score this code runs

if (score == targetscore)
{
   _spawnmanager.Stopenemy();
   targetscore += 20;
}

Which call this function back in Script A.

public void Stopenemy()
{
   SpawnEnemy = false;
}

Script A then stops spawning enemys. And a Boss appears. (Upto this point everything works as it should)

Scripts C tracks the boss. When boss is defeated Script C runs

public void reactor()
{
   reactordestroyed++;

   if (reactordestroyed == 3)
   {
      reactordestroyed = 0;
      SpawnManager.Startenemy(true);
      Destroy(this.gameObject);
   }
}

Which calls this function in Script A

public void Startenemy(bool gonad)
{
   SpawnEnemy = gonad;
}

However SpawnEnemy gets updated within the function and becomes true, but instantly resets back to false. I have Debug.Log on both Void Update and void Startenemy and can confirm the debug in startenemy shows Spawnenemy to be true but the void update never shows it to be true only false. What is supposed to happen is the Spwanenemy changes back to true to allow the IEnumerator to cycle another wave of enemies.

Any Ideas?

Upvotes: 1

Views: 215

Answers (1)

R Astra
R Astra

Reputation: 469

Your code would be constantly calling Stopenemy(); Try changing

if (score == targetscore)
{
    _spawnmanager.Stopenemy();
    targetscore += 20;
}

to

if (score ==targetscore&&bossNotSpawned)
{
    _spawnmanager.Stopenemy();
    targetscore += 20;
}

Upvotes: 0

Related Questions