Can anyone assist with this code? Keeps erroring out...

Godot Version

Godot Engine v4.4.1.stable.official

Question

I am receiving an "Invalid access to property or key 'data' on a base object of type 'Nil'

I have a few scripts -

Data Script:
class_name Data
extends Resource

Contain data to Save and Load.

Current amount of stardust available.

@export var stardust : int = 0

Game Script:
class_name Game
extends Node

Main node of the game.

Singleton reference.

static var ref : Game

Singleton check.

func _singleton_check() → void:
if not ref:
ref = self
return

queue_free()

Contains the data to save and load.

var data : Data

Singleton check & Data initialization.

func _enter_tree() → void:
_singleton_check()
data = Data.new()

Receiving the error on other scripts when trying to do this:

Creates stardust and store it.

func create_stardust() → void:
Game.ref.data.stardust += 1
func _on_timer_timeout() → void:
create_stardust()

Your Game.ref is null at the time of create_stardust(), maybe your singleton_check’s ref variable is different from Game.ref.


Hard to tell without proper formatting, make sure to paste code between three ticks ```

don’t do that. godot has built-in singletons through Autoload. create an autoload in project settings and you can access all its properties and methods from any script at all times.
autoload needs to have a name in snake_case, the autoload can then be accessed by typing the name in PascalCase.
for example:

my_autoload.gd

 MyAutoload.get_stuff()

godot has nodes. nodes exist inside the game tree (after calling the add_child method). autoloads are added automatically to the tree when the game start and exist at a higher tier than the main scene node, and persist after calling methods like change_scene, so they are very good for things like score.

the problems I see here are two:
1 - you are trying to call a property of a class, which I don’t think you can do in godot (not like that at least). you could do it if game was an autoload, but it is a node, and must exist inside the tree.
2 - there is no Game object in the scene because of the time at which the method is called.