Instanciate a node with parameters

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

I have something like

extends Node2D

export (Resource) var this_card
export (Texture) var back_texture = "res://assets/cards/cardBack_red1.png"

func _ready():
	piece_name = this_card.piece_name
	mana_cost = this_card.mana_cost
	$CardControl/Template/Artwork.texture = this_card.artwork

and I wish to instantiate the node from gdscript editing dynamically the resource and texture to set.
But I cannot figure it out how to do it.

I tried with _init(card) but it says :

Cannot convert from Object to int

Can you help me, pleease ?

:bust_in_silhouette: Reply From: camarones

To access a node for instancing that it must be saved as a separate scene. (Right click on it in the scene tree and choose Instance Child Scene). The function _init(): is called once a node has been initialised and cannot be used to instance other nodes. Instead you use "path_to_the_instance_child_scene".instance(), which returns a reference to that node.

From there you can adjust any properties you like before finally adding it as a child of something (it won’t be created until you do this). Here I’ve added it as a child of the object that is doing the instancing, but you could use get_tree().get_root() to put it somewhere else.

var new_card = preload("res://*path of the scene to be loaded*")
export (Texture) var back_texture = "res://assets/cards/cardBack_red1.png"

func _ready():
    var instantiated = new_card.instance() =
    new_card.mana_cost = self.mana_cost
    new_card.get_child(interger_index_of_child_sprite).texture = back_texture