Call a function in another script

Godot Version



Hello there everyone !
I have a trouble calling a function :

I have a script attached to my Character body 2D(with is the player character)
Then I have the Inventory, it is a Node 2D being a child of my Character body 2D.

In the script attached to the Inventory Node I want to call a function being in the script of the Character body 2D but I don’t understand how to call a function in the parent node, it alway give me the error “Invalid call. Nonexistent function in base’NIL’.”

Can somebody help me please ? :slight_smile:

I am a noob but i think it have something to do with signals

my suggestion is that you check out signals so that nodes can talk to each other.

There are many ways to do it. But as others have said, a clean way to do it is using signals.

You can undestand a signal like a way of child to tell ascendants in the object tree something has ocur, so they can react to it.

In your case, in you inventory script you may have this signal:

signal inventory_opened

func open_inventory():

then in your character

func _ready():
  # You will have to add a reference to inventory node with @export or other method
  inventory.connect("inventory_opened", _on_inventory_opened)

func _on_inventory_opened():
  # Play some animation

This is quite simplified example but I hope it helps you as starting point.

1 Like

It can also depend when and how often you want to call the function and if the character body is the direct parent.
For example you may just have to wait until the parent node is fully initialized:

@onready var my_label = get_node("MyLabel")

or you would get the parent node’s method:

var parent = get_parent()

print("Something from the parent", parent.method)

A signal makes more sense when the nodes are not connected and you need to send some information away across the scene tree, IMO.