Using string variable as packed scene

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By lambi

I feel like I might be missing the easy solution here…
I got a dictionary, which includes a key / value par containing the reference to a .tscn. However, during the rest of the code, I cannot access that tscn, since the value gets interpreted as string instead of PackedScene, and so far I’ve failed to convert the value…

var weapon_data = {
"MG1" : {
	weapon_params.damage : 1,
	weapon_params.projectile_speed : 50,
	weapon_params.fire_delay : 1,
	weapon_params.projectile_scene : "res://scatter/bullet.tscn",
	weapon_params.mount : weapon_type.gun
},

[…]

bulletScene = GameData.weapon_data["MG1"][GameData.weapon_params.projectile_scene]

fails with the debugger error “Trying to assign value of type 'String” to a variable of type ‘PackedScene’.

:bust_in_silhouette: Reply From: Enfyna

I dont know your weapon_params variable so I wrote the keys as string.

Godot scene example image

First I loaded the scene.Then I instantiated it.After this you can use this as a child but if you want to use more than one bullet you have to duplicate it.

Code :

extends Control

var weapon_data = { 
		"MG1" : {
			"damage" : 1,
			"projectile_speed" : 50,
			"fire_delay" : 1,
			"projectile_scene" : "res://bullet.tscn",
			"mount":"gun"
		}
	}


func _ready():
	var bulletScene : PackedScene = load(str(weapon_data["MG1"]["projectile_scene"]))
	var bulletInstance : Node = bulletScene.instantiate()
	for i in range(10):
		var bullet : Node = bulletInstance.duplicate()
		add_child(bullet)

that solved it, thanks! I was missing the load(str(…)) part

lambi | 2023-03-24 12:41