Is there a way to add property before instancing?

Godot Version

4.2.2

Question

Hello,

I would like to add a variable to my enemy scene that is called “side_movement”.
This variable describes if the enemy should move sidewards.
I would like this property to be set and saved in a packed scene I am preloading. Meaning that the scene is not instantiated yet. In consequence since instance is “null” I can´t access the var “side_movement”.

Now I am wondering if there is a way around it to set the variable before instantiating it?

Maybe with a class? I have never used classes before though, so I am insecure about this approach.

Thank you in advance!

In Gdscript you cannot add variables during runtime (when your program is running).
What you can do is create the side_movement variable and set the value to false inside the enemy scene script.
Then you can also use @export on that variable to see it in the inspector and set it only for enemies that need it.

If you do want to set it using code, then first instantiate the enemy and then right after do something like: enemy.side_movement = true

1 Like

Hi @tshadow999,

Thanks for the answer. I tried exactly that. But then I can´t set variable before instantiating it. I can only set the variable to true after instantiating.

I want to use the variable as a trigger in _ready() to avoid the need to check for it in _process().

My idea as a workaround is to use a Timer and to check within the signal of the timer if the var “side_movement” is true

Why do you need to set it using code when you instantiate the scene?
You can also create a base enemy node and a sidemovement enemy that inherits from the base scene instead. Then you dont need to set the variable

Then you can change the variable before adding it to the scene tree. _ready() only fires once the node is add_child

var clone = PREFAB.instantiate()
clone.side_movement = false
add_child(clone) # _ready() fires
1 Like

You can’t instantiate a scene with constructor arguments.
However you can set variables after instantiating but before adding to the scene tree.
This will make them available to use in _ready()

var enemy = load("whatever").instantiate()
enemy.side_movement = whatever
add_child(enemy)
1 Like

Dang it, you beat me to it! :stuck_out_tongue_closed_eyes: