godot icon indicating copy to clipboard operation
godot copied to clipboard

Preload function would have to accept a constant string parameter as input.

Open Rocket-Buddha opened this issue 10 years ago • 8 comments

Preload function would have to accept a constant string parameter as input.

const WARM_UP_STATE = "res://scenes/states/warm_up/warm_up.tscn"

func _go():
    current_state = preload(WARM_UP_STATE).instance()
    level.add_child(current_state)

res://scenes/levels/level_01/src/node2d_state_manager.gd:23 - Parse Error: expected string constant as 'preload' argument.

Rocket-Buddha avatar Oct 11 '16 22:10 Rocket-Buddha

Not understanding what you mean.

you could just do:

WARM_UP_STATE = preload("res://scenes/states/warm_up/warm_up.tscn")

then just call it in your function

func _go():
    current_state = WARM_UP_STATE.instance()
    level.add_child(current_state)

vonflyhighace2 avatar Oct 11 '16 23:10 vonflyhighace2

That's right! But IMO it doesn't change the fact that the function should accept a constant string and WARM_UP_STATE is a constant string.

Rocket-Buddha avatar Oct 11 '16 23:10 Rocket-Buddha

I also think it should accept constants even if it's defined in external file (lets say I have singleton with constants)

kubecz3k avatar Oct 12 '16 12:10 kubecz3k

This is amusing. I was going to say something because I am loading an "empty scene" from a string constant in my project. Turns out I was using load() (which works) instead of preload() (which doesn't), making them inconsistent.

magpie514 avatar Oct 12 '16 13:10 magpie514

Well it's normal that load() works as it does not expect a constant. But preload() does, and apparently fails to see a const String as such.

akien-mga avatar Oct 12 '16 13:10 akien-mga

Ah I see, I figured load() would also expect a constant.

magpie514 avatar Oct 12 '16 13:10 magpie514

As i see it, preload function loads the resource when the scene is constructed, for that reason needs a constant input, on the other hand load function loads the resource when it is called.

Rocket-Buddha avatar Oct 12 '16 18:10 Rocket-Buddha

Thanks i use this as my final code..

# Background photo initialization
func initialize_background(image_path: String):
    var background = TextureRect.new()
    
    # Use ResourceLoader to load the texture dynamically
    texture = ResourceLoader.load(image_path)
    
    if texture != null:
        background.texture = texture
        background.rect_min_size = get_viewport_rect().size
        add_child(background)
        background.raise()
    else:
        print("Failed to load texture:", image_path)

sabbir28 avatar Dec 23 '23 03:12 sabbir28