Search Unity

Resolved Unity Singleton MonoBehavior

Discussion in 'Scripting Dev Blitz Day 2023 - Q&A' started by stonstad, Feb 22, 2023.

  1. stonstad

    stonstad

    Joined:
    Jan 19, 2018
    Posts:
    660
    The Singleton design pattern is very useful for maintaining a single instance of an object, i.e. a network connection or a single instance of a game component shared across scripts, i.e. weather system

    Building a proper singleton monobehavior in Unity can be challenging because there are lifecycle management considerations, many of which have unforseen consequences. For example, resetting state between editor playback iterations is needed, but Unity does not reset static state by default.

    I suspect this would be easier if there was a SingletonMonoBehavior base class that handled lifecycle management for developers. What are the team's thoughts around this?
     
    glenneroo and Thaina like this.
  2. Thaina

    Thaina

    Joined:
    Jul 13, 2012
    Posts:
    1,168
    Would that be ECS World and System ?

    I would also utilized RuntimeInitializationOnloadMethod. What I think unity really lacking is SceneLoad attribute and ability to attach component to scene, a SceneComponent
     
  3. echu33

    echu33

    Joined:
    Oct 30, 2020
    Posts:
    62
    While we always write our own solution per project. I too believe a more official sample/implemtation can make developer's life easier.

    By the way -
    Unity's AddressableAsset package has it's own implementation worth check it out -> ComponentSingleton<T>
    A mirror source code can be found here

     
    stonstad and Thaina like this.
  4. Thaina

    Thaina

    Joined:
    Jul 13, 2012
    Posts:
    1,168
    In dotnet 7 there was static interface and virtual. Maybe we should have unity update dotnet for this functionality
     
  5. simon-ferquel-unity

    simon-ferquel-unity

    Unity Technologies

    Joined:
    Apr 1, 2021
    Posts:
    68
    We are working on some new editor-lifecycle related apis. One of them is something ressembling this:

    Code (CSharp):
    1. public class PlayModeScoped<T> where T:class, new(){
    2.    public static T Get();
    3. }
    It will enable you to write singletons that are automatically reset on each playmode session (and for player builds, they behave as a pure singleton).

    The constraint here will be you'll need to have a default-constructible class for a T (so not a Component, more like a vanilla C# object).
     
  6. stonstad

    stonstad

    Joined:
    Jan 19, 2018
    Posts:
    660
    This would be AMAZING! Thank you!