Class Variables vs Declaring in Functions

It seems inefficient to declare variables in OnCollisionEnter2D and HandleHits (isBreakable and maxHits) when they are unchanging. This will cause them to be recreated every time those functions are called.

Is there any reason not to use a private class variable that is initialized in Start()? The only thing I could think of was the potential to use the Inspector to change those values while the game was paused and have them take effect immediately. I’m not sure that would balance out the inefficiency.

I think not. The MaxHits can be calculated once in Start. The calculation is simple and the code in this case is simple but if you had a complex routine then it would be inefficient to re-calculate the value every time.

In this case however, it makes little difference. I personally left it as a private variable because while the scope of where the variable is used is limited, it is simply more efficient to have it a class member variable.

If the length of the array changed during execution, that would be different. It doesn’t however.

I came here to ask this same question.

It seems more efficient to me, to declare the variable only once, in the start function, rather than declaring it on each hit, so I have done that even though it probably makes almost no difference in this case. Where I can make my code more efficient with very little effort, I always feel compelled to do so.

Somewhat off topic, if you ever find yourself using multiple declarations of “yield return new WaitForSeconds(5);” or similar, you can declare that variable once instead and it can make a significant difference.

There’s different kinds of efficiency. Accepting that we’re dealing with small effects in this example, but thinking of the wider theory:

  • initialising new variables each time a function is called is cpu intensive
  • maintaining a class variable that’s initialised at start is memory intensive

In the case of HandleHits which will be called a maximum of 3 times per brick, the alternative is to allocate the variables in memory for every brick for the entire game until they’re destroyed.

In that example I’d probably make this change to avoid the unnecessary int declaration, but wouldn’t use a class variable either:

...
// int maxHits = hitSprites.Length + 1;
  if (timesHit > (hitSprites.Length)) {
...