How to get children nodes within a base/super class

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By colonlc
:warning: Old Version Published before Godot 3 was released.

I got a base Level class with a method to count specific child nodes, but this method cannot acces the children of the node which has a inheriting class attached to it. So how do I get the instance of my child class

Level.gd → Level1.gd (Node2D) → children

EDIT:
Figured out the solution: you cannot acces child nodes in the _init() function, just did it in _ready()
Thanks anyway

:bust_in_silhouette: Reply From: avencherus

I don’t have any issues with doing something like:

Base:

extends "level.gd"

func _ready():
	print(count_nodes("Sprite"))

Super (level.gd):

extends Node

func count_nodes(type):
	
	var count = 0
	
	for node in get_children():
		if(node.is_type(type)): 
			count += 1
		
	return count

Yes, that is working, but I want to do call it in the base class, so I do not have to write it into each level script

Level1.gd

 extends "level.gd"

    func _ready():
    print(count_nodes("Sprite"))

Level.gd

var collectable_count

func _init():
    collectable_count = count_nodes("collectable")

func count_nodes(type):

    var count = 0

    for node in get_children():
        if(node.is_type(type)): 
            count += 1

    return count

colonlc | 2017-05-19 16:51

Well that depends on when and how you’d like it to be called, but as an example you have the options to specify when a node is initialized, entering the tree, readied, or exiting the tree.

Init happens as soon as you make a new class, enter tree is when you add it to the scene tree, and ready happens when it is made ready in the scene tree, and exit when it is removed.

func _init():
func _enter_tree():
func _ready():
func _exit_tree():

So if you want it to happen on ready when it enters the scene tree in the level.gd base class, just move the ready code there.

func _ready():
    print(count_nodes("Sprite"))

If you want something more particular, you will have to decide and design the conditions you want.

avencherus | 2017-05-20 15:19

For the ones coming in 2023 with Godot 3.5:

node.is_type(type)

becomes:

node is type

d2clon | 2023-02-19 17:38