Skip to content

Invoke method of instance events in a Singleton becomes no longer callable in static context. #11

Description

@chris24xd

Assume we have this simple singleton.

using UnityEngine;

public class ExampleSingleton : MonoBehaviour
{
    public static ExampleSingleton Instance {get; private set;}
    public event Action ExampleEvent;
    
    private void Awake() => Instance = this;
    public static void InvokeExampleEvent() => Instance.ExampleEvent?.Invoke();
}

When adding the [Singleton] attribute to the class and doing the appropriate changes, the Invoke method for ExampleEvent is no longer callable, because now Instance is an interface instead of an instance class.

using UnityEngine;
using EngineRoom.Runtime.Singleton;

[Singleton]
public class ExampleSingleton : MonoBehaviour
{
    public event Action ExampleEvent;
    
    public static void InvokeExampleEvent() => Instance.ExampleEvent?.Invoke(); // No longer possible!
}

This is only solveable if you change the method to a non-static one, making ExampleEvent directly accessible in its own class. What if you really wanted to keep code simpler and use a static method for this purpose?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions