How to spawn an object in a location from an array of possible points?

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

I tried to google for this, but couldn’t find the terms I needed, I think, every result was random spawning.

Here's my node tree, just to be sure.

I’m trying to spawn an enemy instance at the position of a predetermined point, where I have each point as a Position2D node named Spawn1 - Spawn 8, and they’re all the child of a Node2D called Spawnpoints. My script is on the root node, a Node2D named SpawnManager. My code looks like this:

extends Node2D

onready var enemy1 = preload("res://Enemies/Enemy.tscn")
onready var SpawnPoints = $SpawnPoints

var possiblePoints = SpawnPoints.get_children()
var selectedSpawn 

func _on_EnemySpawnTimer_timeout():
	selectedSpawn = possiblePoints[rand_range(0,7)]
	var Enemy_instance = enemy1.instance()
	Enemy_instance.position = selectedSpawn.position

When I run it, I get the error "Invalid call. Nonexistant function ‘get_children’ in base ‘Nil.’ "

:bust_in_silhouette: Reply From: exuin

The problem is, the SpawnPoints node is not assigned to the variable until the node SpawnManager is ready. possiblePoints is trying to access the children of SpawnPoints before that happens. You should assign possiblePoints after SpawnPoints is assigned, in the _ready() function.

Thanks so much! This helped out a lot. As you can tell, I’m still kind of a newb with this. The timing is weird. I ended up adding a bunch of print statements as troubling shooting for other areas of my code and this fixed a lot of them. Thank you so much!

crookedvult | 2021-01-21 12:28