How to call a function in a child node from the code of the parent child

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Sheggif

Hello! I want to call a certain function called “Close_Spike” from my parent node.
Code:
Parent:
extends Node2D

func _on_Player_Close_Spikes():
get_children()

Child:

extends Area2D

const Open_Spike_Sprite = preload(“res://Assests/Tile Set/Open Spike.png”)
const Spike_Holder_Sprite = preload(“res://Assests/Tile Set/Spike Holder.png.png”)

func _ready():
Close_spike()

func Open_spike():
$Sprite.texture = Open_Spike_Sprite
$CollisionPolygon2D.disabled = false

func Close_spike():
$Sprite.texture = Spike_Holder_Sprite
$CollisionPolygon2D.disabled = true

func _on_Spike_body_entered(body):
if “Player” in body.name:
body._died()

func _on_Lazer_Open_spike():
Open_spike()

func _on_Lazer2_Open_spike():
Open_spike()

func _on_Lazer3_Open_spike():
Open_spike()

func _on_Lazer4_Open_spike():
Open_spike()

:bust_in_silhouette: Reply From: mburkard

Hello,

The best way to go about this can vary depending on the full situation.
If the parent node has one or more children and you want to call “Close_Spike” on all of them you could do that with this:

func onPlayerCloseSpikes():
    for child in get_children():
        if child.has_method("Close_Spike"):
            child.CloseSpike()

The “has_method” will prevent errors in the situation that the parent has other children that don’t have that method defined.

If the parent has multiple children and you only want to call “Close_Spike” on one of them, you will need some way of getting the name or other identifying piece of information to check against each child when looping through the children.

This answer is so underrated! Thank you for this!

t8 | 2021-11-13 18:49

1 Like