I have to disagree that ‘avoid caching where possible’ should be applied. Caching is extremely important, especially when doing things such as GetComponent.
The nice thing about Components is that Unity overrides the getter so that it returns null
when it is destroyed in the engine, so that is already a good thing.
Secondly, if you write methods, make it so you always have a setter for variables, and those setters can refresh the cache. If the DoubleWidthAndHeight()
method would just call SetWidth()
and SetHeight()
, nothing would be the problem because those setters should respectfully update the cache.
What I do think is that a cache should be simplified and abstracted. If you keep track of booleans for isInAir
and isOnGround
… then consider the fact that one can never be true when the other is true. So, in other words, simplify the state. One cache can already answer the other. (consider using a state machine (enum or class based) when going into boolean hell)
My conclusion:
Write unoptimized code first, then optimize where you can when you do your second coding pass (don’t overdo it, but don’t call GetComponent
in the update loop etc). And keep it as simply and confined as possible. Don’t set variables directly of the global scope, always have a method which sets them so that cache data can be updated.