How to use class,I can't get node

hi,there
I try to use class to build my program, like below

extends Node

class_name barrier

var sp
var coll

func _init(picpath,fnode,si):
             # pos is position , picpath is picture path , fnode is parent node , si is size
	sp=Sprite2D.new()
	coll = CollisionShape2D.new()
	sp.texture = AdjectPic(picpath,si)
	coll.shape = RectangleShape2D.new()
	coll.shape.extents = sp.texture.get_size()/ 2
	
	fnode.add_child(sp)
	fnode.add_child(coll)
func AdjectPic(pic,si):
	var image = Image.load_from_file(pic)
	image.resize(si, si,0)
	var texture = ImageTexture.create_from_image(image)
	return texture

extends RigidBody2D

class_name Chessman
var bar = preload("res://class/barrier.gd")
var che
func _init (pos,picpath,fnode,si):
    # pos is position , picpath is picture path , fnode is parent node , si is size
	che = RigidBody2D.new()
	var b = bar.new(picpath,che,si)
	che.position=pos
	fnode.add_child(che)

extends Node2D
#it's my main sence
var che = preload("res://class/Chessman.gd")
var role
# Called when the node enters the scene tree for the first time.
func _ready():
		
	
	role = che.new(Vector2(99,99),"res://pic/chessman.png",self,44)
	print(role.get_child_count())

the result is zero , I can’t get any child node,but I don’t know why

A script will not contain the scene information. You need to preloaded the .tscn file

But since you procedurally add nodes just make sure to add_child for each node class you call new() on.

Looking at you code you add them to fnode. And not che. So it will not have any children. Also you create a bar but don’t add it as child.

In my main scenes, I preload the “chessman” class and instantiate it, using the nodes in my main scenes as parameters.

In the “chessman” class (which is another script), I preload the “barrier” class and instantiate it, creating a new Rigidbody2D to be used as parameters.

Last, in the “barrier” class (also another script), I instantiate Sprite2D and CollisionShape2D, and add them to the fnode Rigidbody2D as child nodes.

And then, I go back to the “chessman” class and add the Rigidbody2D to the fnode, which are the parameters, a node that I sent from my main scenes.

This is the flowchart I believe I created.

And when I return to the main scenes, I want to print the role’s child nodes, but I get zero. However, if I use “print(self.get_child_count())”, I can get it

I solved it

After the line “role = che.new(Vector2(99,99),“res://pic/chessman.png”,self,44)”, I used an array called “roles” to remember my child nodes. However, instead of using “roles.append(role)”, I used “roles.append(self.get_child(0))”.

Initially, I thought the “role” would be the node, so I used it as the parameter. However, it turned out not to be the case, and then I figured out that I did not write any return value.

1 Like

think you for your help . it’s helpful.