Preload() not working properly

Godot Version

Godot Engine v4.3.stable.steam.77dcf97d8

Question

I need to create a minefield. Each mine is a separate object created in a random location. I used preload(“path”) to load an object from a file and add() to add the loaded object and then assign it a random position and add it to the tree using add_child(). The problem is due to the fact that mines are assigned to a tree and are visible through get_tree_string(), but they are not visible in the game. Next I will attach screenshots of the code and trees. Thanks in advance for your help.


image
image

You’re loading an script and probably what you want is load the entire scene, your probably saved this as mine.tscn, try to load this instead:

extends Node2D
var p_mine = preload("res://mine.tscn")
var window_size = Vector2(1154, 648)

func _ready() -> void
	for i in range(randi()%16+5):
		var mine = p_mine.instantiate()
		mine.position = Vector2(randi()%int(window_size.x-30)+15, randi()%int(window_size.y-30)+15)
		$enemies.add_child(mine)
5 Likes

Thanks! Don’t know why i didn’t notice that befor.

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