I have been tearing my hair over the past few days trying to fix this error and possibly have tried everything in existence. Please help me find the error.
I am making a 2d runner game in Godot, and I have auto-loaded the HUD tscn so its visible up top in all pages.
I want to change the score everytime the user body enters the coins but it returns the following error in the coin script:
I have followed a youtube tutorial on this and theirs all work but mine does not.
Here is my file system hierarchy:
I don't know why it says its a null instance. Its obviously not null.
func _on_Coin_body_entered(body):
if body.name == "Player":
get_node("/root/main").score += 5 #not working for some reason
var tween = create_tween()
tween.tween_property(self, "position", position + Vector2(0, -30), 0.5)
tween.tween_property(self, "modulate:a", 0.0, 0.5)
tween.tween_callback(self, "queue_free")
```
And the MainHUD script:
```extends Node2D
var score = 0 setget set_score
onready var lives = 3 setget set_lives
func set_score(value):
score == value
get_node("/root/main/HUD/Score").set_text("SCORE: "+str(score))
func set_lives(value):
lives == value
$HUD/Lives.set_text("LIVES: "+str(lives))
if lives <= 0:
#change scene to dead scene
print("hello")
pass
Here is a final photo to show the contents of the label:
Any help would be really appreciated. Thankyou
Edit
The autoload page is the MainHUD tscn. the one that contains the lables shown in the image above
The reason it is not working, is that your path in get_node is wrong. You added an autoload scene with the name "Hud" not "main"
On start the autoload scenes will be added to the root node with their name.
So the path to your scene is "/root/Hud" not "/root/main".
Additionally you have to make a change in your setter functions:
lives == value
and score == value
have to be lives = value
and score = value
, since you want to update the respected variable to value
and not to check if the value of lives is the same as value
This being said, your scripts would look like this:
func _on_Coin_body_entered(body):
if body.name == "Player":
get_node("/root/Hud").score += 5 #not working for some reason
var tween = create_tween()
tween.tween_property(self, "position", position + Vector2(0, -30), 0.5)
tween.tween_property(self, "modulate:a", 0.0, 0.5)
tween.tween_callback(self, "queue_free")
and your hud:
extends Node2D
var score = 0 setget set_score
onready var lives = 3 setget set_lives
func set_score(value):
score = value
$HUD/Score.set_text("SCORE: "+str(score)) #no need to get_node from root so I changed it as used in set_lives
func set_lives(value):
lives = value
$HUD/Lives.set_text("LIVES: "+str(lives))
if lives <= 0:
#change scene to dead scene
print("hello")
pass