Example of how Singleton works

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

I have 20 levels (racing tracks) and EACH OF THEM needs to have the Last Lap and Best Lap stored permanently. Currently, I have a script that starts counting Current Lap and restarts it once “Finish Line” crossed, no problem so far. But I need to store the Last Lap and Best Lap values (time) in a global (singleton) script that will enable me to keep the last values every time I start the track. I will highly appreciate the time you spend explaining to me and others facing the same problem how to achieve it may be with simple examples. Especially how local and global scripts communicate.

:bust_in_silhouette: Reply From: deaton64


It’s not as complicated as it may appear.
Create a file called Global.gd and autoload it as a singleton, as explained here: Singleton

Then you could put something like this in your Global.gd:

extends Node

var best_lap = [10.1, 18.2, 14.3, 9.9]
var a = 10

func _ready() -> void:
	print("I'm the Global ready function")

func best_lap_time(_track: int) -> float:
	return best_lap[_track]

I’ve done a print in the Global._ready() function so you can see when it runs.

Then to access variables and functions, you add Global before the variable name. So to access the array best_lap all you need to do is something like: track0_best_lap = Global.best_lap[0] or the a var, Global.a = 20

To use functions, you call them like this: print Global.best_lap_time[1]

Hopefully that all makes sense. Let me know if it doesn’t :slight_smile:

Tons of thanks, mate!

Suleymanov | 2020-06-06 10:53