Is there the possibility of having a race condition when counting blocks?

Is there the possibility of having a race condition when counting blocks?

This might be an advanced concept this early in the course, but I was wondering what would be the best way to avoid it? I was thinking maybe adding a Lock() in the critical section, but maybe there is a simpler and more efficient way of solving it.

Hi Rodrigo,

My understanding of Unity’s threading system is fairly limited but I believe, we get effectively a single thread in which all MonoBehaviours execute, under the hood Unity uses multithreading to run their own jobs. This is changing with the advent of ECS, however, I’m fairly confident this isn’t an issue for you at this time.

You have a couple of alternatives to making the numerous method calls across scripts to increment the number of blocks in the scene, you could;

  • using FindObjectsOfType<Block>().Length - returns an array of the specific objects, this wouldn’t differentiate between breakable/non-breakable, but you could just another script to each block to determine that
  • using FindGameObjectsWithTag - again, returns an array, you could get the count, you could then use tags to differentiate between breakable/non-breakable, would provide limited functionality though without the need for creating many tags and more complex logic to determine different block types. You would also need to be careful that you don’t inadvertently tag the wrong GameObjects creating breakable blocks that the player will never be able to break (an Empty for example being used as a container).

Note - all of the Find methods are not overly performant as they have to cycle through every object in the scene, you’d only want to do this kind of approach once, and typically at the start of the game.

  • you could have the count of Blocks as a variable within the Block class itself, make it static so that the variable belongs to the class and not an instance of the class, and then simply increment/decrement that value from within the class during Awake and when it is destroyed. You would need to carefully manage this to avoid issues where levels do not change because you’ve made an error and your game believes there are blocks left.

Hope this helps :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms