This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

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
in Engine by (16 points)

1 Answer

0 votes

In your function onTimertimeout(), you writed this :
enemy.position = rand

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"]


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.

by (526 points)
edited by

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.

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.