unity – Is there a approach to serialize subscriptions to occasions (C# Actions)?

unity – Is there a approach to serialize subscriptions to occasions (C# Actions)?

[ad_1]

I’ve many situations of a category that instantiates prefabs that solely exist within the editor. When this occurs, an occasion is invoked to alert subscribers that issues are being instantiated:

utilizing UnityEngine;
utilizing System;

public class GameObjectCreator : MonoBehaviour 
{
    [SerializeField]
    personal GameObject _prefab;

    public occasion Motion<GameObject> OnCreated;

    public void Create()
    {
        var clone = Instantiate(_prefab);
        OnCreated?.Invoke(clone);
    }
}

I’m pairing this class with a couple of helper lessons which have completely different duties for establishing these clones; these helper lessons additionally exist solely inside the editor. I’m utilizing OnValidate to subscribe to the OnCreated occasion, which permits all the things to work inside Unity, however issues break in an precise construct.

public class CreationHelper : MonoBehaviour
{
    [SerializeField]
    personal GameObjectCreator _creator;

    personal void DoSomeStuff(GameObject gameObject) 
    {
        // ...
    }

    personal void OnValidate() 
    {
        _creator.OnCreated += DoSomeStuff; // That is misplaced at runtime
    }
}

I do know I can merely use a supervisor for added setup inside a given scene, however am questioning if there’s a approach to serialize occasion subscriptions so I can proceed with this present construction.

I don’t imagine UnityEvents will work as a result of they require concrete references to issues within the scene, and I’m instantiating an unknown variety of prefabs at runtime.

[ad_2]

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply