-1

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)

2 Answers2

1

$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
NeZvers
  • 110
  • 7
0

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.

ouflak
  • 2,458
  • 10
  • 44
  • 49
Carlos
  • 1