I have a main scene and a unit_storage scene that contains all the units I intend on using and a UI to go with the units (displays information and their actions etc etc.) I would like to know if it’s possible to instantiate specific parts of this scene such as spawning in a unit when it is purchased.
I think the answer is yes, but it is a little difficult to understand what you mean exactly.
Is it possible to instantiate specific nodes in a scene?
Yes, you can create any specific node you want directly like say:
var new_label: Label = Label.new()
add_child(new_label)
This is where it starts to get a little confusing. So all the ‘units’ are already in your tree? So do you actually mean ‘instantiate’?
Hmm. If it is already in your tree, why would you want to instantiate it? But yes, lets say you have a ‘unit’ scene, you can instantiate that into your tree if the player is allowed to access it.
No, you cannot instantiate a ‘part’ of a scene. Only self contained scenes or .tscn files.
I would have somewhere a list of units the player has available. Each unit would be it’s own scene. If the player activates the unit, that is when you would load it in (instantiate the unit scene) into the game for the player to use.
I think to help any further we would need more concrete examples of what you mean exactly. Sorry.
I’ve organized all the units into a scene that stores all their information (health, movement, actions, etc.) and I was wondering if I could instantiate a node (unit) that is a part of the storage scene.
For example, I have a swordsman that is stored in the unit_storage scene and when the player purchase this unit one should spawn in, I was wondering if it would be possible for the main scene to instantiate the swordsman from the unit_storage
Then you can get any unit scene from that array. In this example, UNITS[0] would be a swordsman scene.
Instead of using rather arbitrary integers as indices, you can use an additional enum to have comprehensible names.
enum {
SWORDSMAN,
ARCHER,
#...
}
You can use any names you want here. The important thing is that for each unit, the position in the enum matches the position of its scene in the array. The enum and the array need to have the exact same order. Then you can access the unit scenes like this: UNITS[SWORDSMAN]
Using a dictionary instead of an array would allow to use other values than integers as keys (e. g. strings), but that doesn’t seem necessary here.
Depending on how large the sum of all unit scenes is and how often they get instantiated, it could be better to only store the file paths of the scenes and load them dynamically before instantiating the unit. But unless you have immediate performance issues, that should be checked and opitimized later.