All Find() methods are going to be an overhead, as such, you want to minimise them where-ever you can.
If @Assistenten’s example is in the
Start() method on the Brick object, then it is setting that static variable every single time a Brick is instantiated. So, a level with 200 bricks will call the
FindGameObjectsWithTag() method 200 times and 199 of them will not be required as you have already set the variable to equal 200.
Arguably, you could put a check around it to see if it has already been set. You might initially set breakableCount to -1 instead of 0 (zero), and then within the
Start() method only perform the find if it no longer equals -1. You would, of course, need to reset this to equal -1 before loading the new levels instead of 0. We would use -1 insetad of 0 (zero) as you require 0 (zero) for checking that all of the bricks have been destroyed if they are breakable.
public static int breakableCount = -1;
void Start ()
if(breakableCount = -1)
breakableCount = GameObject.FindGameObjectsWithTag("Breakable").Length;
When I consider all of the things we are now having to do to facilitate the ease of using the
.Length property of the collection returned by the
FindGmeObjectsWithTag() method, it’s not feeling as straight forward as just checking the tag for the brick that was instantiated and using
isBreakable = (this.tag == "Breakable");
// keep track of breakable bricks
…the above seems straightforward, sufficient and doesn’t require additional validation to prevent the performance issues.
I hope this is helpful.
Updated Sat Jun 24 2017 19:08
You may also get an error if you were to create a scene with no breakable bricks - I know you wouldn’t typically have this because it wouldn’t be a playable/winable level - but according to the Unity documentation null will be returned if nothing is found with corresponding tags, as such you would be trying to then access the
.Length property of a null object, which should cause an error immediately.
Potentially therefore, you should protect against that with some more code too!