How to use functions in an autoload singleton class

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

Hello,
so i want to create a class that gives me access to:

  1. functions interacting with variables in the class
  2. variables in the class that are global

The problem now is, if i access said class like this:
FileSystem.someVar
everything works as expected.

If i however want to use a function like FileSystem.someFunc() i get this as an error:
error: Non-static function ‘someFunc’ can only be called from an instance.

If i do access it like this:
var fileTest1 = FileSystem [or var fileTest1 = get_node(“/root/FileSystem”)]
fileTest1.someFunc
it works, which in itself is weird, because this shouldn’t (and seemingly doesn’t as you can see in the following) create an instance like the error demands.

I could use this since the variables still act as global and are not an instance, but the autocompletion does not detect any members of FileSystem then, which is really painful. (It also doesn’t detect any members in the first access-example, but i wanted to inform to make the situation clear)

I cant make the functions static since i need to use the variables outside the functions.

The autocompletion suggests if i use FileSystem, that i follow that up with new() as the only func, however new() doesn’t work since i never declared that.

Also i would want to know why it is not possible for the static function to access these variables, since they also at least act as static.

Are you defining a class_name at the top of your script file AND adding the script to the Autoload list? I’m pretty sure an Autoloaded script is created as an actual instance, which is just globally accessible. If you are also defining the class_name, try removing that and see if it works.

Eric Ellingson | 2019-04-09 17:37

Thank you, that was the problem.

I never thought about that, although now it kinda makes sense.

Alidro | 2019-04-09 18:04