Topic was automatically imported from the old Question2Answer platform.
Asked By
Michael McCrickard
I have an exported String var called color. I want to specify the color with a string in the editor. If the var is “red”, I load a red texture into my TextureProgress. Or “blue” for my blue texture, etc.
I am able to see the exported var in the editor and enter the string. And I can set the texture in ready(), but for some reason, my if test on the exported var color is failing. The code is very simple:
export var color:String = ""
func _ready():
var tx
if color == "blue":
tx = load("res://blueBar.png")
$VerticalBar.set_progress_texture(tx)
If I leave the if test out, then the texture gets set, but not with the if test.
That does it! In reading the docs about load vs. preload, I can’t see why this wouldn’t work but the lesson learned seems to be, Don’t use load() in the ready() function? Use preload() instead?
Michael McCrickard | 2022-03-09 14:57
Okay so what I am about to write is not 100% correct but it is a good way of thinking about it.
Load essentially means you are running the set up of the scene at that point, so in your original code you have a var which you are saying is a load of a scene. What happens effectively is the scene loads in the background but isnt added to your main running scene so it just runs silently in the background but a var cannot be a scene so the var is now null. It has already run the code to load the scene.
Preload on the other hand creates a scene silently but then adds effectively a link to the var which says load this scene I have now created.
In essence load runs straight away so if you use load you have to add it to the scene straight away, preload allows you to have a link to a scene but effectively actually load it later as you did in your code with
$VerticalBar.set_progress_texture(tx)
Gluon | 2022-03-09 15:14
Thanks very much for this detailed answer. This seems related to some of the info I was reading last night about “Applying Object Oriented Principles in Godot”, like “Scripts are not technically classes. Instead, they are resources that tell the engine a sequence of initializations to perform on one of the engine’s built-in classes”. Clearly, the initialization aspect is critical.