Techno's_elbow
Techno's_elbow

Reputation: 11

Error message "Invalid set index 'text' (on base: "null instance") with value of type 'String' " when trying to change the text of a label

i am trying to update the text of a label but keep getting the above error message. i don't know what i am doing wrong. here is my code:

extends Node

var PlayerScore = 0
var EnemyScore = 0

func _on_Left_body_entered(body):
    $Ball.position = Vector2(640,360)
    EnemyScore += 1

func _on_Right_body_entered(body):
    $Ball.position = Vector2(640,360)
    PlayerScore += 1


func _process(delta):
    $PlayerScore.text = str(PlayerScore)
    $EnemyScore.text = str(EnemyScore)

Upvotes: 0

Views: 13161

Answers (2)

Carlos
Carlos

Reputation: 1

The solution that I implemented was to put the Label in another scene.

You will decide if you put it above or below the scene you are using.

I do not understand why it happens but for some reason it does not allow to read or update the text in a main scene. It usually happens to me in the scenes that it starts to execute.

Upvotes: 0

NeZvers
NeZvers

Reputation: 120

$PlayerScore is shorthand for get_node("PlayerScore") which means it checks direct child with name "PlayerScore". Your error shows that (on base: ”null instance“) which means that you were accessing null instance (it doesn't exists, at least as direct child or at that moment).

P.S. Since you are calling it that often I'd suggest save the reference to that node in a script's global variable.

onready var playerScore: = $PlayerScore #variable will be created when script's owner is ready

Upvotes: 1

Related Questions