Why do I get the error "Can't call non-static method from signal <name_of_signal>" when trying to emit a signal?

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

Hi forum,

Question
When my program tries to emit a signal it gives the following errors. Any ideas why?

call: Can't call non-static function '_on_signal' in script.
emit_signal: Error calling method from signal 'the_signal'

Background

I have two scripts, call them primary and secondary. In primary I connect a signal the_signal to a function in secondary by

# primary.gd
var secondary = load("res://secondary.gd")
signal the_signal()

func _ready():
    self.connect("the_signal", secondary, "_on_signal" )

and in secondary I have the receiving function

# secondary.gd
func _on_signal():
    # doing some stuff
:bust_in_silhouette: Reply From: njamster

Because a non-static function always refers to a particular instance. However, in your case there’s no such instance! So either make the function static…

# secondary.gd

static func _on_signal():
    print("It works!")

… or create an actual instance of the script with new():

# primary.gd

var secondary = load("res://secondary.gd").new()
signal the_signal

func _ready():
    self.connect("the_signal", secondary, "_on_signal" )
    emit_signal("the_signal")
    secondary.test = 2
    emit_signal("the_signal")

# secondary.gd

var test = 1

func _on_signal():
    print("Test: %d" % test)

Worked like a charm =)

toblin | 2020-03-24 06:46

:bust_in_silhouette: Reply From: WolframR

There’s another way this can happen i think. if you accidently refer to a script when connecting signals instead of a node. the two are separate.