Avoiding race conditions

Hey!

I have a level where I want to keep track of all the enemies still active in the scene (they come in waves and I count them to zero to start a new wave).
At the moment I have a variable in a script that tracks all level data that keeps count of how many there are:

  • when a wave of enemies is created it
    adds to the var (varName++ for each
    spawned enemy)
  • when an enemy is destroyed the
    enemy’s script accesses that var and
    reduces it by one

Now and then I get a race condition.

I was thinking of simply using FindGameObjectsWithTag to check instead, but I’m worried it will be too expensive to check each Update().

Hm, the code of all MonoBehaviours should be safe, as it’s executed in a single thread. It shouldn’t be possible for race conditions to occur due to concurrent access.

Not sure if that’s also the case if you use classes that are not derived from MonoBehaviour.

However, it will be a problem if you have asynchronous external events accessing Unity objects (e.g., Network et al., unless it uses Polling from within an Update()), or use threads.

In that case, to answer your question, use semaphores:

private int count=0;
private Object semaphore=new Object();

void Increase(){
    lock(semaphore){
        count++;
    }
}

void Decrease(){
    lock(semaphore){
        count--;
    }
}