Ah, see, this is what I first thought as well the first time I encountered similar issues, but it’s actually not what’s happening. When you define a normal variable like this:
var imanumber = 5
the variable is created and its value is assigned on the same line, but more to the point, both of these things are actually happening at this time, exactly as the code suggests it should.
@export
variables do not work this way, which is counter-intuitive because the code is in the same format. It does indeed feel like a bug, but only because we expect @export
variables to follow the same pattern as normal variables… because why on earth wouldn’t they?
It’s not that the default value is overwriting what the inspector shows; rather, the default value is all that the game has at the moment this line is executed because it hasn’t even checked the inspector yet. The purpose of using @onready
in the way we both did is basically to tell the game to wait until the inspector is read (and therefore max_hitpoints
receives its true value) before using max_hitpoints
to assign a value to hitpoints
.
@export
variables absolutely have their place (great for quick prototyping for example), but yes, I barely use them in general. There are a few inherent problems with @export
variables, but there’s pretty much always a way around using them in the first place, and each problem can still be overcome without doing so:
- Not scalable, unless you’re specifically using them in a template of some kind that will be inherited or instantiated by something else dynamically… and in that case, is it really necessary to use
@export
variables instead of normal ones? Maybe, but I can’t see an example.
- If a field is left empty by mistake and you don’t set a default value in code, it’s almost certain your code will break. Writing your own exception-handling can fix this (checking if empty during
_ready()
for example).
- If you do have a default value and you change the value in the inspector, there is nothing in your code that will indicate you are using a non-default value. I ran into that one face-first during Kaan’s Alien Attack. This is harder to solve (console output is one solution during development), but again just comes down to the context in which you’re using the variable.
Hope that all makes sense =)