Need help with a enemy spawner

Godot Version

Question

need help making this code work. I’m trying to make enemies spawn on 2 spawners on the left and the right. I’m trying to spawn enemies on the global position of these spawners which I get from .globalposition. I used global position before with no error so I really don’t know why sometimes it works and sometimes does not.

var spawn_left = Leftspawn.global_position
var spawn_right = Rightspawn.global_position

var score

func newgame():
pass

func _process(delta):
pass

func _on_rightspawntimer_timeout():
var new_enemy = ENEMY.instantiate()
get_tree().current_scene.add_child(new_enemy)
new_enemy.global_position = spawn_right

func _on_leftspawnertimer_timeout():
var new_enemy = ENEMY.instantiate()
get_tree().current_scene.add_child(new_enemy)
new_enemy.global_position = spawn_left

If your enemy is RigidBody2D/3D, setting position directly is unpredictable, try to sync it as, but it is not granted

new_enemy.set_deferred("global_position", spawn_right)
...
new_enemy.set_deferred("global_position", spawn_left)

Just realized, as you add enemy to root node, you can use

var new_enemy = ENEMY.instantiate()
new_enemy.position = spawn_right
get_tree().current_scene.add_child(new_enemy)

let me clarify. the problem is that im getting errors like this linking to the global position and how its not giving the position and just null.
image

The message about new_enemy is null, so godot can not find property global_position

i am reading ENEMY so I assume it’s a const which is a bad idea because it’s actually a packedScene resource that needs to be loaded in on runtime for example like this:
var ENEMY = load("PATH-TO-ENEMY.tscn")

I would first set a breakpoint at var new_enemy = ENEMY.instantiate() and then see if new_enemy stays null or has an actual value

the const was not the problem. Still the only problem is the global position not actually working

Which line of code causes the error? If it’s the first two lines, try adding @onready to your variables:

@onready var spawn_left = Leftspawn.global_position
@onready var spawn_right = Rightspawn.global_position

What it does is tell Godot to not try to set that variable until the scene tree is fully loaded.

For that matter, how do you even get the references to Leftspawn and Rightspawn?

THanks for the suggestions but i was starting to be annoyed so I brute forced this problem by putting in the literal cords of the sprites as a variable and fixed this. i will try the on ready solution and see if it works on other things .

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