How can I do something if a function of a child's script is called?

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

Tree:

Gamemode1 (script attached)

  • BaseGame (instance, script attached)

In BaseGame’s script I have the function game_over(). I want to do something when game_over() is called but I want to do this at Gamemode1’s script. How?

:bust_in_silhouette: Reply From: njamster

GameMode1.gd

extends ...

func _ready():
    $BaseGame.connect("game_over", self, "_on_BaseGame_game_over")

func _on_BaseGame_game_over():
    # do something

BaseGame.gd

extends ...

signal game_over

func game_over():
    emit_signal("game_over")

If you don’t want to use signals, you could also call the parents method directly:

GameMode1.gd

extends ...

func _on_BaseGame_game_over():
    # do something

BaseGame.gd

extends ...

func game_over():
    get_parent()._on_BaseGame_game_over()

Edit: Fixed the code for game_over in the second example.

You mean in BaseGame.gd
get_parent()._on_BaseGame_game_over right? Or do I misunderstand?

MaaaxiKing | 2020-06-18 13:41

Yeah, my bad, sorry. I correct my answer accordingly.

njamster | 2020-06-18 14:08

What if the parent doesn’t have this function? This is also sometimes, in other modes.

MaaaxiKing | 2020-06-18 14:51

second question’s answer → just add if get_parent().has_method("_on_game_over").

MaaaxiKing | 2020-06-19 14:45