Invalid set index 'text' (on base: 'Nil') with value of type 'String'.

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

When I’m trying to change the label text in function ‘set_score_text’, the game crashes and gives the following error: Invalid set index ‘text’ (on base: ‘Nil’) with value of type ‘String’. What prevents me from setting text to the labels in the set_score_text function?

extends Control

onready var mainscene = load("res://MainScene.tscn").instance()

onready var scoreText1 = get_node("Label_0")
onready var scoreText2 = get_node("Label_1")
onready var scoreText3 = get_node("Label_2")

func _ready ():

scoreText1.text = str("x 0")
scoreText2.text = str("x 0")
scoreText3.text = str("x 0")

func set_score_text(id, amount):

if id == 0:
	scoreText1.text = str("x ", amount)
elif id == 1:
	scoreText2.text = str("x ", amount)
elif id == 2:
	scoreText3.text = str("x ", amount)

I just ran into the same issue. I have a sprite with a child label. It’s a sign post that I want to be able to set the text in the designer.

tool
extends Sprite

export(String, MULTILINE) var label_text = "" setget set_label_text, get_label_text

onready var lbl = $Label

func set_label_text(value):
	lbl.text = value

func get_label_text():
	return lbl.text

DigitalMan | 2022-06-15 13:04

:bust_in_silhouette: Reply From: jgodfrey

The error means that you don’t have a valid reference to one of your scoreText labels. So, at the point where you do this:

scoreText1.text = ...

Your scoreText1 (or one of the other 2 label references) is NULL. That means that this code isn’t acquiring a valid reference to your Label nodes:

onready var scoreText1 = get_node("Label_0")
onready var scoreText2 = get_node("Label_1")
onready var scoreText3 = get_node("Label_2")

It’s hard to offer more input without know 1) what your scene tree looks like and 2) what node the above script is attached to.

Anyway, the Label references are bad.

My scene tree looks like this:enter image description here

The UI node is attached to a CanvasLayer node in the MainScene.tscn.

ajonat99 | 2022-02-11 07:12

And what node is the posted script attached to? By the looks of the posted scene tree, I assume it’s attached to UI? But, if that’s the case, the code looks correct. Verify what node the script is attached to.

Also, I’ll mention that the indentions in the posted script are incorrect, but I assume that’s just a cut/paste issue in the forum…

jgodfrey | 2022-02-11 15:30

Hmmm… Looking closer, I see that you’re setting the text values of your 3 labels in the _ready function, which (apparently?) IS NOT failing, which would indicate that your label references are working as expected.

With that in mind, it’s not obvious to me what’s wrong here. Is the project available somewhere for closer inspection?

jgodfrey | 2022-02-11 18:57