Spawn points for enemies

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

I want an enemy to spawn at one of four random locations but this code will give me an invalid set index ‘position’ (on base: kinematic2D) with value of type ‘int’ error

extends Node2D
var options = [$Position2D, $Position2D2, $Position2D3, $Position2D4]
var rand_index:int = randi() % options.size()
onready var enemy = $Enemy


func _on_Timer_timeout() -> void:
enemy.position = rand_index
:bust_in_silhouette: Reply From: ponponyaya

In your function _on_Timer_timeout(), you writed this :
enemy.position = rand_index.

The question is that the type of position is Vector2, but the type of rand_index is int.
You can’t assign an int variable to a vector2 variable.

—update following—

Ok, you says you got null when you print(options).
I think that’s because array can’t contain node element.
You should use “String” with function get_node().
I mean you can do like this following:

var options = ["Position2D", "Position2D2", "Position2D3", "Position2D4"]

...(Skip)

func _on_Timer_timeout() -> void:
	enemy.position = get_node(options[rand_index]).position

(or you can use “global_position” to replace “position”.)

This way in my test is fine, hope this help.

thanks! I think this fixed one of my problems but, options is returning null for me when I print it. It tried getting the tree then the node but that didn’t work.

merpis | 2022-01-22 16:39

Ok, I think I know what’s wrong with “options”, I updated the answer, you can take a look at the new info.

ponponyaya | 2022-01-23 01:20