Topic was automatically imported from the old Question2Answer platform.
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
$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')
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)