Static property in singleton?

Godot Version

4.3

Question

Could a static property like Health is bad design, and why?

public partial class Global2 : Node {
  public static Global2 Instance { get; private set; }

  public static int Health { get; set; } = 10;

  public override void _Ready() {
    Instance = this;
  }
}

It would be used like this

Global2.Health -= 10;

A bit faster then accessing Instance.

Don’t worry to much if you make small projects and first games.
problems what can case:

  • Global state is harder to track
  • Breaks encapsulation
  • Harder to manage multiple instances
  • Difficult to test
1 Like

in godot, use an autoload. an autoload is a singleton created by godot, it generates a single node at the root that persists between scenes.
it can be accessed from any node.

I would question the reason for this code to exist, a singleton is used for an object that needs to be the only instance of a class, and health is usually part of a character, and you have many in a game at a given time.

I would add that you should not worry about performance, that’s premature optimization, it’s a waste of time.