Skip to content

Services

Valk edited this page Sep 19, 2024 · 25 revisions

Using the static keyword in GameServer.cs for all attributes may initially seem convenient for accessing game server properties across different parts of the code. However, this approach poses significant challenges. When the server restarts or transitions between scenes, static properties retain their values, causing inconsistencies.

Manually resetting each static property to address these issues is cumbersome and error-prone. This demonstrates the need for careful consideration when using static properties, as they can simplify initial development but complicate maintenance and scalability.

In the _Ready() method of any node, you can register the node with Global.Services by using Global.Services.Add(this) (or Global.Services.Add<Type> if the script does not extend from Node).

public partial class UIVignette : ColorRect
{
    public override void _Ready()
    {
        // Set 'persistent' to true if this script is an autoload
        // Scripts that do not extend from Node are persistent by default

        // Non-persistent services are removed just before a scene change
        // Example of a persistent service: AudioManager, which should exist
        // throughout the game's duration

        // This UIVignette is part of the scene, so it should not be persistent
        Global.Services.Add(this, persistent: false);
    }

    public void LightPulse() { ... }
}

With this setup, you can now retrieve the instance of UIVignette from anywhere in your code without relying on static properties or lengthy GetNode<T> paths.

UIVignette vignette = Global.Services.Get<UIVignette>();
vignette.LightPulse();
Clone this wiki locally