How should we reference a function from another script?

Godot Version

4.4.1

Question

Hello, i’m new here and I have an interrogation about how should I refer to a custom function that I made from another script (that don’t attached to any nodes) ?

I don’t know if I have expressed myself clearly.

here an exemple of what i’m saying:

image

I write this inside my “player” script but it doesn’t seem to be working…

(“Handeling” is the class_name of a script that i want to refer and “connection()” is the function that i made in this same script.)

If you want help with your code, please show us all the whole file. Copy and paste it with ``` on the lines above and below the code like this:

```
#Code here
```

And it will appear like this:

#Code here

Based on what you are saying, it sounds like you are referring to your Handeling class incorrectly - but I don’t know.

If Handeling is a class name, don’t use the dollar sign in front of it. That would look like a reference to a node. And you probably have a typo in the function name. The correct syntax would be Handeling.connection().
However, you still cannot call a function this way unless you make it static or you add the handeling script to the autoload list.

1 Like

If you want to go the static function route as suggested by @FencerDevLog:

in Handeling.gd

class_name Handeling extends Object
static func connection() -> void:
      blabla

Then
Handeling.connection()
should work

Ok, I made an “onready var handeling : Handeling = $…” on top of my script and it seems to be working but I have another problem:

Inside my Handeling script, I need to make reference to a CharacterBody2D named “friend” Which is located in an other scene but here is the error that I recieved when I run the code:

… … …

I tried many times to understand but that look very confusing for me…
Sorry , my english is not so good so maybe i don’t understand all of your message but thank you everybody for your interest !

here is the error message:
image

The message is clear. You are trying to assign $“.” Handeling Node to a Friend type variable. You need to assign Friend.new() The Friend class must exist as a class_name in some other .gd file or you need to preload the gd containg the.

friend_class.gd

class_name Friend extends Object

func _init(value: int):
    print("Friend initialized with value: ", value)

your script:

var friend := Friend.new(10)

Also you can preload the Friend.gd file using the preliad

your script

var Friend = preload("res://friend_class.gd")
var friend = Friend.new(10)
1 Like

Thank you, it was helpfull, I have other problems but I will try to fix them with experience. :waving_hand: