I want to make a cache when a mono is created.
However, Mono does not allow constructors. How can I fire an event when a mono is created?
thanks.
I want to make a cache when a mono is created.
However, Mono does not allow constructors. How can I fire an event when a mono is created?
thanks.
as @MUG806 already described you can use Awake
or Start
when this happens. I guess i’d personally use a Action
for this and call it in Awake
. Awake is called before Start and has the benefit that it is also called if the GameObject with the Component on is created with enabled = false
.
public class MonoBehaviourWithEvent : MonoBehaviour {
public static System.Action OnMonoCreated;
public void Awake(){
OnMonoCreated?.Invoke();
}
}
So then you can have some function
public void functionToExecuteWhenMonoIsCreated() { Debug.Log("MonoCreated"); }
which you can subscribe to the action:
MonoBehaviourWithEvent.OnMonoCreated += functionToExecuteWhenMonoIsCreated;
Hope this helps, let me know if you have questions regarding this or something is unclear.
First, Thanks for answer.
But what I want is to call the event before Awake’s call.
call MonoCreateEvent() //User Custom Function
call Awake() //Unity native Function
I don’t think Unity has support for that.
What you can do is create an extension method on gameObject that adds the new mono and then calls your event.
For instance, instead of calling:
GameObject.AddComponent<Mono>();
You can call:
GameObject.AddComponentWithEvent<Mono>();
Where AddComponentWithEvent first calls the regular GameObject.AddComponent and then calls your event