+1 vote

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

in Engine by (13 points)
edited by

1 Answer

+1 vote

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
by (5,232 points)

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

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.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.