How to make a Godot-style singleton #233
-
Hi there, Is Singleton possible as it is in vanilla Godot? Is there a Nimonic way of doing this? I'm a bit new to it so I'm not sure if there's a proper way. What I'm doing at the moment is create a Global type in a file called global.nim and I simply "import global" whenever I want to use it in other files. It doesn't feel like a global object I can access anytime though. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Your method is best for use with Nim only. That is, the following pattern # globals.nim
type Global* = object
value*: int
var global*: Global import gdext
import gdext/classes/gdNode
import globals
type Main* {.gdsync.} = ptr object of Node
method ready (self: Main) {.gdsync.} =
global.value = 10 If you want to refer to it from GDScript as well, you need to devise a way to do so using the Godot mechanism. # globals.nim
import gdext
import gdext/classes/gdEngine
type Global* {.gdsync.} = ptr object of Object
value* {.gdexport.}: int
var global*: Global
proc register_Global_singleton {.execon: initialize_scene.} =
# This callback is called from initialize_scene by the execon macro.
# initialize_scene is an event to register the new class with the engine when this extension is loaded.
global = instantiate Global
Engine.singleton.registerSingleton("Global", global)
proc free_Global_singleton {.execon: eliminate_scene.} =
Engine.singleton.unregisterSingleton("Global")
destroy global import gdext
import gdext/classes/gdNode
import globals
type Main* {.gdsync.} = ptr object of Node
method ready (self: Main) {.gdsync.} =
global.value = 10 class_name Main
extends Node
func _ready():
Global.value = 10 |
Beta Was this translation helpful? Give feedback.
Your method is best for use with Nim only. That is, the following pattern
If you want to refer to it from GDScript as well, you need to devise a way to do so using the Godot mechanism.