Problem with singleton and timer

extends Node

var TempoGloball = 0

func _on_timer_timeout():
TempoGloball +=1

works correctly before making a singleton,
when added as a singleton the print displays 01 02 03 04 05, and if called in another scene it displays only 0

I think you should instantiate the scene in runtime.
The singleton is only instantiated the root node.
Its same in NodeName.new().

Could you be more detailed please?

There is a scene:

A (a.gd)
 |- Timer
 |- Others

It can be instantiated by these ways:

  • PackedScene.instantiate() → A
A (a.gd)
 |- Timer
 |- Others
  • A.new() → A
A (a.gd)
  • Set A as singleton
A (a.gd)

Singleton is a special way for A.new(), it will be added to scene tree in game start.

So in last 2 ways, the Timer node and other nodes will be dropped and it will not emit signals.
That explained why you can’t received signals and use get_node to get child nodes.

in this case I attached the script directly to the timer and made it the singleton, but the error is the same, you can try to experimen
Captura de tela 2024-01-31 161921
t

I don’t saw any problem in my case:

Console output

Godot Engine v4.2.1.stable.official.b09f793f5 - https://godotengine.org
OpenGL API 4.5 (Core Profile) Mesa 21.2.6 - Compatibility - Using Device: AMD - AMD HAINAN (DRM 2.50.0, 5.4.0-169-generic, LLVM 12.0.0)
 
Timer: 0
Timer increase
Timer: 1
Timer: 1
Timer increase
Timer: 2
Timer: 2
Timer increase
Timer: 3
Timer: 3
Timer increase
Timer: 4
Timer: 4
Timer increase
Timer: 5
Timer: 5
Timer increase
Timer: 6
Timer: 6
Timer increase
Timer: 7
Timer: 7
--- Debugging process stopped ---

Files

res://
 |- icon.svg
 |- main.gd
 |- main.tscn
 |- singleton.gd

singleton.gd

extends Timer

var timer: int = 0;

func _ready() -> void:
    timeout.connect(_on_self_timeout)
    start(1);

func _on_self_timeout() -> void:
    timer += 1;
    print("Timer increase");

  • make singleton.gd as a singleton named Singleton

main.gd

extends Node2D

var time_passed: float

func _process(delta: float) -> void:
    time_passed += delta
    if time_passed < 0.5:
        return
    time_passed -= 0.5
    print("Timer: " + str(Singleton.timer))

scene tree(main.tscn)

Main - Node2D - main.gd

scene tree(Runtime)

root - Window
 |- Singleton - Timer - singleton.gd
 |- Main - Node2D - main.gd