How to use class,I can't get node

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
	coll =
	sp.texture = AdjectPic(picpath,si)
	coll.shape =
	coll.shape.extents = sp.texture.get_size()/ 2
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/")
var che
func _init (pos,picpath,fnode,si):
    # pos is position , picpath is picture path , fnode is parent node , si is size
	che =
	var b =,che,si)

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

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 =,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.