Cannot call a function from another class

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

I can call the class, but how do I call the function?

This is the code for the class I want to call.

#MyClass.gd

class_name MyClass

func FuncA():
	pass

I want to call FuncA in this class.

#Player.gd

extends KinematicBody

func _ready():
	
	var myClass = MyClass.new() #Non Error.
	
	myClass.FuncA()	#This is Error.

Sorry for the elementary question. Am I missing something?

:bust_in_silhouette: Reply From: jgodfrey

UPDATE - The below answer was based on a misunderstanding of the original question. See the conversation in comments below for more helpful information. (I wish the forum supported strike-through text for better visibility here…)


You’re probably running into the same misunderstanding as described (and resolved) here:

https://forum.godotengine.org/16097/how-do-you-call-class-methods-from-an-external-gdscript-file

I have done the same but it does not work.
its Q&A seems to have calling a script, but I seem to have calling a reference on my end.
Also, what is the difference between “class” and “class_name”?

huny | 2022-04-15 16:34

Hmmm… Sorry, looks like I misread your post. What you show should work as expected.

If I create a file named MyClass.gd with this content:

class_name MyClass

func FuncA():
	print("Called FuncA")

… and then, from another script, do this (for example):

func _ready():
	var myClass = MyClass.new()
	myClass.FuncA()

The function is called and I see called FuncA printed in the console. Is what you’re doing somehow different?

jgodfrey | 2022-04-15 16:42

To your earlier question class_name just registers a name (and, optionally, an icon) for the class represented by the current script. Theclass keyword creates an inner class.

Search for those terms here for more info: https://docs.godotengine.org/en/stable/tutorials/scripting/gdscript/gdscript_basics.html?highlight=class_name

jgodfrey | 2022-04-15 16:49

I was trying different things and it worked!
As a matter of fact, I had named the class StateMachine (for clarity for questions).
It did not work with the name StateMachine, but it worked fine with the names MyStateMachine and StateMachine_.

I didn’t understand what was going on, but it worked anyway. Thank you for your patience.

huny | 2022-04-15 17:05