Godot 4.0 Get function isn't working

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

This is the error output: “Cannot call non-static function “get()” on the class “res://CardsDatabase.gd” directly. Make an instance instead”

I don’t understand why this isn’t working, if i try to call it with get_instance() function it doesn’t work either

extends MarginContainer
@onready var CardsDatabase = preload(“res://CardsDatabase.gd”)
var Cardname = ‘CardExample’
@onready var CardInfo = CardsDatabase.DATA[CardsDatabase.get(Cardname)]
func _ready():

:bust_in_silhouette: Reply From: Hanate

When you use preload, you get the class CardsDatabase. This is a class, not an instance.

To use ‘get’, you need to create an instance. There is two options for that :

  1. Create a local instance, using var myCardsDatabase = CardsDatabase.new(). You can then use myCardsDatabase.get(...). This instance is local, meaning it will be re-created in each scene instance.

  2. Create global instance using autoload your CardsDatabase.gd script into you project. For this, go to menu Project/Parameters, then Autoload tab, and hit the “Add” button. Now, CardsDatabase will be instantiate and available globally in all your scripts, thus you can remove @onready var CardsDatabase = preload("res://CardsDatabase.gd"). This instance is shared between all your scenes and instance, and can be used to share data between them.

As your class is called CardsDtatbase, I guess you you want to share data between multiple scenes / instances, in which case you should go for solution 2.

Thanks, but I tried the same code(what didn’t work in the latest version) in the 3.5 version and it worked without Problems. Is this just the solution for the new version of godot?

DG_Games | 2023-04-02 21:55

I can’t say how this worked in 3.5, I haven’t use that version version a lot. As far as I know, the Autoload was already available in this version, but maybe there was something else that let your code work.

However, the error message is pretty clear, and consistent with the documentation. The preload function returns a Resource (which is in your case, a Script), which you need to instantiate to use non static functions.

Autoload is (one of) the recommended way to share data between scenes, and, as far as I understand your use case, the way I think you should go

Hanate | 2023-04-02 22:26