0 votes

Hi, I have a main scene with player and enemies. I added both enemy and player scene under main scene in the editor. Now in script I can access the position of player with following code

$Player.position

Now the thing is I removed the player added in the editor. And now I am adding the same player at runtime by instancing it.

   export (PackedScene) var Enemy

   var player = Player.instance()
   get_tree().get_root().call_deferred("add_child", player)

Now I try to get the position of player as follows

$Player.position

It is not working as expected.The error is

Invalid get index 'position' (on Base: 'null instance')

Any solution. Thanks in advance....

in Engine by (112 points)

1 Answer

+1 vote

Here's a quick example of what you need. Generally it's always a good idea to store nodes that you create in your code in a variable, if you need to access them later on.

extends Node2D

export (PackedScene) var PlayerScene

# variable where we store the player
var player


func _ready():
    # create the player and store it in the "player" variable
    player = PlayerScene.instance()

    # no need to use "call_deferred()", you can add a child like this
    # replace "Main" with the name of your root node in the main scene
get_tree().get_root().get_node("Main").add_child(player)



func _process(delta):
    # now you can get the player position from the variable like this:
    print(player.position)

Hope this heps :)

by (111 points)

this is what the exact solution am looking for.

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 webmaster@godotengine.org with your username.