Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | CFR_Godot |
Hi everyone!
I’ve got a bit of a hangup with my code that I thought it might be an idea to get the community’s input on:
Is it beneficial for my code to avoid setting a variable every frame?
For example, in my current project I have a “lock-on indicator” which is a Sprite3D that isn’t visible by default. The following code is run every frame on the player character to only have this indicator be visible when we’re targeting an enemy:
if !has_target() and LockOnIndicator.visible == true:
LockOnIndicator.visible = false
elif has_target() and LockOnIndicator.visible == false:
LockOnIndicator.visible = true
As you can see, I’m trying not to constantly set the node’s visibility - it only gets set once when the exact requirements are met, and the cycle just bounces off the if statements every other time.
Is this actually beneficial or am I okay to just have the visible variable be set again on every frame?
-CFR
Generally, if you can avoid setting something every frame then, being lazy developers, you wouldn’t do it. That is, if you don’t need to do the work then don’t do it.
An alternative here may be to that has_target
runs some event code (like from a signal) than can change the visibility of an object when required, freeing up just that little bit more processing time for other important things in your game. But perhaps you might want to do this; only you can decide if this is important for your game.
As you’re aware, your if statements might be entirely false so won’t set the variable anyway. You could optimise then slightly for the sake of readability; e.g. testing has_target
twice isn’t necessary - if !has_target
is false then has_target
must be true so the call is unnecessary.
spaceyjase | 2023-02-14 11:57