How to instance a node from another scene?

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

Hi all.

I want to build a simple card game and trying to build a nodetree based database. I have a scene called CardDB which olny stores one card so far a Sword. StaticBody2D type node with sprite and so.

My problem is that I cannot instance the Sword in my Battle scene if I want to reach it trhough a path. I manage to locate it and print it on the debug window but cannot put it on the screen. If I want to put the CardDB on screen (var card) then it shows the card but if I want to show the Sword card directly it does not show. Could you point me to some direction what am I doing wrong?

extends Node

var card = preload(“res://Scenes/CardDB.tscn”).instance()
onready var card_one = card.get_node(“Sword”)

func _ready():
$Path2D/PathFollow2D2.add_child(card_one)
card_one.connect(“one_damage”, self, “_on_CardBody2D_one_damage”)
print(card_one.name)

:bust_in_silhouette: Reply From: kidscancode

You can’t use card.get_node("Sword") before you’ve added the card to the scene tree.

First, you’ve made card an instance of the CardDB scene (which contains several nodes). These nodes must be added to the tree if you want to access them.

The next problem is, you’re trying to use add_child() on one of the subnodes of card.

Presumably, you have a number of cards as children of CardDB. Try this: add CardDB to the tree and then use show() and hide() to show the particular card you want.

It’s hard to give you any more specific advice without knowing more about your setup. I would recommend reviewing this doc which covers the basics of instancing scenes.

PS - please format your code by placing four spaces in front of it when you post a question, so that it appears

get_node("Like this")

and the underscores and indentation aren’t stripped away.

Thanks it helped. Now the card is showing on the screen. I still cannot put it on the path yet but one step closer :slight_smile:

konkoj | 2019-02-07 16:31