Reference node when instantiate

Godot Version

Godot 4.2

Question

hey, i’m trying to spawn enemy into my main scene, but the problem is the enemy script has a line that look like this

func _physics_process(delta):
	# Get the direction towards the player
	var player_position = $Player.global_position
	direction = (player_position - global_position).normalized()

normally it works fine, but if i tried to instantiate the scene, it give me error
Invalid get index “global_position”(on base: ‘null instance’.

basically what i was trying to accomplished is

  1. spawn the enemy
  2. make the enemy follow player.

also this is how i intantiate it

func _on_timer_timeout():
	var Enemy= enemy.instantiate()
	add_child(Enemy)
	Enemy.position = $Spawn_1.global_position

How does your scene tree look like? If you get this error, it means the node path you’re using is wrong! That is, the node your script is attached to, does not have a direct child called “Spawn_1” at the time this function is run. Therefore, get_node (and it’s short form using just $) returns a null instance instead of a node, which obviously doesn’t have the global_position property (or any other property) you’re trying to set.

this is how my tree look like, spawn 1 and 2 is just for marking the spawn position
image_2024-05-04_205449962

The _physics_process function you posted above is in your enemy script, but referencing $Player, which only would work if the Player was a child node of your enemy, which is probably isn’t. Doing get_parent().get_node("Player") instead should work in your case, but might break if you change the tree structure. A better way would be to set a variable in your enemy scene when instantiating it, that holds a reference to the player node:

func _on_timer_timeout():
	var Enemy= enemy.instantiate()
	Enemy.player_node = $Player
	add_child(Enemy)
	Enemy.position = $Spawn_1.global_position
var player_node

func _physics_process(delta):
	var player_position = player_node.global_position
	direction = (player_position - global_position).normalized()

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.