How to get position of a Node that is added programatically?

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

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


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


It is not working as expected.The error is

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

Any solution. Thanks in advance…

:bust_in_silhouette: Reply From: eddex

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

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

Hope this heps :slight_smile:

this is what the exact solution am looking for.

anbarasu chinna | 2020-09-13 00:00