Set the text on a label in an instance

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

This function complains: Invalid set index ‘text’ (on base: ‘Nil’) with a value of type ‘String’. I don’t understand why.

extends KinematicBody2D

onready var registration = $Label

func set_ship_registration(text):
    registration.text = text

when set_ship_registration(text) is called in Main:

func generate_ship(scene, x, y, reg):
    var ship = scene.instance()
    ship.position = Vector2(x, y)
    ship.set_ship_registration(reg)
    add_child(ship)

There’s a sample project here: GitHub - imekon/text1: Sample of Godot error

:bust_in_silhouette: Reply From: nucky9

Hi,

You need to parent your ship before you can access it, so you just need to move your add_child(ship) so that it comes after you instantiate your ship.

@nucky9’s answer is correct. and @imekon you need to know what the onready keyword does.
GDScript — Godot Engine (3.0) documentation in English

volzhs | 2018-10-13 19:28