How to Initialize Exported Properties?

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

I created a class called Card. It has 2 properties, title and image. When they are changed, it also changes a Label node and a TextureRect node respectively (they are children of the card). My goal is to ease the card design in the editor for non-programmers so as they need not touch the underlying components.

It works well in the editor, but not at runtime. I have the error “get-path: Cannot get path of node as it is not in a scene tree.”

I suspect it is because when instancing the card, the children are not yet created, whereas in the editor they are already.

How could I solve this particular problem?


To reproduce, set the title property of the Card class in the editor to “Test”.

The files are:

# Game.gd
extends Node

onready var Card = preload("res://Scenes/Card.tscn")

func _ready():
	for i in range(10):
		var card = Card.instance() # <-- crashes here (Stack 1)
		card.position.x = i * 50
   		add_child(card)

And:

# Card.gd
tool
extends Node2D

export(String)  var title setget set_title
export(Texture) var image setget set_image

func set_title(new):
	title = new
	$Outline/Title.text = new # <-- crashes here (Stack 2)

func set_image(new):
	image = new
	$Outline/Image.texture = new
:bust_in_silhouette: Reply From: skysphr

Simply instancing the card should not trigger either of the setters, unless you have a default value, or you’re triggering them manually inside _init() or something.

Yes, I set the default value “Test” in the editor. I edited the question to make it clearer.
So, how can I set a value in the editor and have it propagate to the children at runtime?

Stamm | 2021-09-05 19:01

In that case you could simply check whether the child exists before updating their value: if not has_node("Outline"): return

skysphr | 2021-09-05 19:16

Ok, it works now. Thank you :slight_smile:
Would you know of a less verbose design pattern by any chance to achieve this? I’m new to Godot.

Stamm | 2021-09-05 21:21