How to instantiate objects and add them as child in a class instance?

Godot Version




I have a function in a custom class to duplicate a 3d node then adding it into as child.

(“grid” is just a list of object array that holds some pregenerated position etc data)

extends Node3D
class_name HexMap
var geo

func _init(_geo):

func generate(geo):
    var inst = geo
    for h in grid:
        var obj = tgen(inst, h)

func tgen(tile, h: obj):
    var h = tile.duplicate()

Then I use this to generate the objects in a Node3d object in the scene (atatched as a script to it)

var geo= preload ("res://prop.tscn")
func _ready():
    var inst_geo = geo.instantiate()

The problem I have is that I do not see the generated objects that have been added as a child ( add_child(obj) ) in the scene. I can run that generator in the actual scene node, that but that gets convoluted for me since I am trying to solve all that in that class.

what am I doing wrong? When I print the child of “scene_object” I see that it lists those objects as childs but not visible in the viewport.

extends Node2D
var m_scene = preload("res://test.tscn")
func _ready():
	var v_instance = m_scene.instantiate()
	# do stuff with sprite2d within scene
	var v_sprite_2d : Sprite2D = v_instance.get_node("MySprite");
	v_sprite_2d.position = Vector2(200,200)
	#and color rect
	var v_color_rect : ColorRect = v_instance.get_node("MyColorRect");
	v_color_rect.position = Vector2(400,400)

1 Like

Thanks but that is not my question, I am trying to instance/duplicate/create an object in an actual custom class and trying to add that object under the scene object that “custom class” is initiated.