How can I make a spawner with specific coordinates?

Godot 4.0

Hello. Firstly, sorry for my bad English. I’ve just started Godot and I want random things to spawn in a certain area. I wrote a code with what I learned from the internet, but it doesn’t work. In that:

extends Node2D(the world)

var object = load(“res://kaya.tscn”)

var dot = [Vector2(100,0), Vector2(0,100)]



var newobject = object.instance()

newobject.set_position (dot)


I’m very newbie, please help.

You can try this, remember to set the template in the editor.

extends Node2D
@export var template: PackedScene

var min_pos = Vector2(0, 0)
var max_pos = Vector2(500, 500)

func _ready():
	var random_x = randf_range(min_pos.x, max_pos.x)
	var random_y = randf_range(min_pos.y, max_pos.y)

	var new_object = template.instantiate() as Node2D
	new_object.position = Vector2(random_x, random_y)


Thanks but I said my English was bad. What is “PackedScene”? Will I write something else instead?

@export tells the editor that this variable can be set from inspector.

PackedScene tells the editor that the variable can be set to a scene. packedScene is the class name of the scene resource.

If you like, you can leave out @export and PackedScene and just use the

var template = preload("res://xxx")

I did it! Thanks for everything. God bless you.

1 Like