0 votes

I'm trying to access main node from another scene and nothing works.
That's the scene path copied from file system

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.

in Engine by (35 points)

1 Answer

+2 votes

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()

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

by (21,539 points)

Thanks for your answer!

What I'm trying to do is, I have a "medpack" scene that is area2D and I want, using "onArea2Dbody_enter ( body )" change Players health.
-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!

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.

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.