Home Game Development unity – Is there a way to serialize subscriptions to events (C# Actions)?

unity – Is there a way to serialize subscriptions to events (C# Actions)?

0
unity – Is there a way to serialize subscriptions to events (C# Actions)?

[ad_1]

I have many instances of a class that instantiates prefabs that only exist in the editor. When this happens, an event is invoked to alert subscribers that things are being instantiated:

using UnityEngine;
using System;

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

    public event Action<GameObject> OnCreated;

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

I am pairing this class with a few helper classes that have different responsibilities for setting up these clones; these helper classes also exist only within the editor. I am using OnValidate to subscribe to the OnCreated event, which allows everything to work inside Unity, but things break in an actual build.

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

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

    private void OnValidate() 
    {
        _creator.OnCreated += DoSomeStuff; // This is lost at runtime
    }
}

I know I can simply use a manager for additional setup within a given scene, but am wondering if there is a way to serialize event subscriptions so I can continue with this current structure.

I do not believe UnityEvents will work because they require concrete references to things in the scene, and I am instantiating an unknown number of prefabs at runtime.

[ad_2]

Previous article Dragon’s Dogma 2 Joins A Divisive Gaming Trend
Next article Box Art Brawl – Duel: Batman: Vengeance (GBA)
Hello there! My name is YoleeTeam, and I am thrilled to welcome you to AmazonianGames.com. As the premier destination for all things related to Amazon Games' universe, we are dedicated to providing you with the most exciting and immersive gaming experiences out there. From captivating visuals to exhilarating gameplay, our website is packed with comprehensive insights, updates, and reviews to keep you ahead of the game. Whether you're a seasoned gamer or new to the scene, I am here to guide you through this virtual frontier. If you have any questions or suggestions, feel free to reach out to me at john@yoleesolutions.com. Embark on your Amazon gaming journey today with AmazonianGames.com and let the adventure begin!