[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]