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

Godot Version

4.2.2

Question

Hi

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)

map.gd

extends Node3D
class_name HexMap
var geo

func _init(_geo):
	geo=_geo
	generate(geo)

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

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

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

scene_object.gd


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

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()
	add_child(v_instance)
	
	# do stuff with sprite2d within scene
	var v_sprite_2d : Sprite2D = v_instance.get_node("MySprite");
	v_sprite_2d.position = Vector2(200,200)
	print(v_sprite_2d.position)
	
	#and color rect
	var v_color_rect : ColorRect = v_instance.get_node("MyColorRect");
	v_color_rect.position = Vector2(400,400)
	print(v_color_rect.position)

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.