Can't acces node from another scene

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By dejvid_bejlej
:warning: Old Version Published before Godot 3 was released.

I’m trying to access main node from another scene and nothing works.
That’s the scene path copied from file system
res://Scenes/Player/Player.tscn

I tried doing it like that:

onready var player = get_node("res://Scenes/Player/Player.tscn")
onready var player = get_tree().get_root().get_node("res://Scenes/Player/Player.tscn")

and few other ways, it always show’s null. Accessing node from current scene works.
I know it’s a stupid question but I can’t get it to work.

:bust_in_silhouette: Reply From: kidscancode

A saved scene file is not the same thing as a node.

get_node() is used to reference a node that currently exists in the scene tree. For example, if you have a “Main” scene, and you instance your player scene in it, you can reference the player with get_node("Player").

If you need to instance a scene that has been saved, that can be done using the UI by using the Instance button (its tooltip says “Instance a scene file as a Node”), or in code like so:

onready var player_scene = preload("res://Scenes/Player/Player.tscn")

func _ready():
    var player = Player_scene.instance()
    add_child(player)

You didn’t include what your scene setup is, so you’ll have to adapt accordingly.

Thanks for your answer!

What I’m trying to do is, I have a “medpack” scene that is area2D and I want, using “on_Area2D_body_enter ( body )” change Players health.
So:
-There’s main scene containing Player scene and Medpack scene
-Player collides with medpack
-In medpack script:

func _on_Area2D_body_enter( body ):
	if body.get_name() == "Player":
		player.health += 50

I tried using your code, but it just created additional players, removing add_child(player) made it do nothing.

How can I access players “health” variable" from medpack scene?
Thank you again!

dejvid_bejlej | 2017-11-26 23:10

You almost had it. body is the name assigned to the colliding body. You’re checking if body is the player, if it is just increment the body’s health:

func _on_Area2D_body_enter( body ):
    if body.get_name() == "Player":
         body.health += 50

Tip: Next time you ask a question, if you’re more specific and include code like this, it’s a lot easier for people to figure out what you really need, rather than trying to guess.

kidscancode | 2017-11-26 23:14

Thanks, it worked! And sorry for not being clear, I’ll try to explain better next time :slight_smile:

dejvid_bejlej | 2017-11-27 00:56