How do I make my Stage 2 Work ?

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

Hello Guys ! I just finished creating Stage 1 of my game and it works just fine. But now I am making Stage 2 and I am not able to run it because I have used this to display score on screen when my player collects item :

 onready var scorelabel = get_tree().root.get_node("Stage1").get_node("CanvasLayer/RichTextLabel")

and also I have used this in my Player Life bar Script :

func _physics_process(delta):
	value=get_tree().root.get_node("Stage1").get_node("Player").playerhp

If I change “Stage1” in these to “Stage2” then obviously Stage 1 wont work ! How can I fix this ?

:bust_in_silhouette: Reply From: njamster

The answer depends a great deal on where exactly the script snippets you provided are located exactly. I’ll assume the following tree for my examples:

Stage1 (or Stage2 later on)
  - Player
  - HUD
    - Score
    - HP

Now if you’re running a script attached to the Player-node and want to get the scorelabel no matter if Stage1 or Stage2 is active, you could do:

get_parent().get_node("HUD/Score")

Analogous if you attach a script to the HP-node and want to get the player’s hp regardless of the currently active stage and its name, you would do:

get_parent().get_parent().get_node("Player").hp

or (the same thing but shorter):

get_node("../../Player").hp

This works around your problem by providing a relative path (starting in the node the script is attached to) instead of an absolute path (starting in the root-node). However, it will still fail if you change your tree without changing the pathes, e.g.:

Stage1 (or Stage2 later on)
  - Node2D
    - Player
  - HUD
    - Score
    - HP

In order to make your scenes completely independent of their exact position in the tree, you would simply emit signals on certain events (scoring a point, getting hurt, etc.) that other nodes interested in that information can connect to.

I used your way for Score and It’s fine but in Life Bar Script of player I keep getting error that No “Player” node found.

func _physics_process(delta):
    value=get_tree().root.get_node("Stage1").get_node("Player").playerhp

This works fine but just for stage 1.

This is Image of My Stage 1 Scene

This is Image of my Player Scene

I have no idea how to get value stored in playerhp in the Life Bar script without using the previous statement containing Stage 1.

Scavex | 2020-04-18 13:30

Assuming your “Life Bar Script” is attached to the node PlayerProgressBar it’s:

func _physics_process(delta):
    value = get_parent().get_parent().playerhp
    # or value = get_node("../..").playerhp for short

njamster | 2020-04-18 13:46

You are a true champion !

Scavex | 2020-04-18 13:51