- Home /
Other
Can a function derived from MonoBehavior subscribe to a static delegate?
If I declare a delegate like
public static event Action <GameObject> OnChange;
Can Destroy(GameObject) subscribe to it, like
OnChange += Destroy;
The reason that it's static is so that it can easily be accessed from other scripts.
Answer by Tobychappell · May 26, 2018 at 09:07 PM
Yes but all subscriptions to the event will try to destroy the one gameobject that is passed into it.
An alternative is to have a parameter-less Action event and encapsulate the Destroy(this.gameobject) in a lambda expression
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyComponent : MonoBehaviour
{
public static event Action OnChange;
public static void CallOnChange()
{
if (OnChange != null)
{
OnChange();
}
}
private void Awake()
{
OnChange += () => Destroy(gameObject);
}
float timer = 3;
private void Update()
{
timer -= Time.deltaTime;
if (timer <= 0)
{
OnChange();
}
}
}
public class OtherClass
{
public void SomeMethod()
{
// Below raises compiler error
MyComponent.OnChange();
// Use a static relay to call the event, although I think this goes against how C# was designed but hey ho.
MyComponent.CallOnChange();
}
}
Sorry, I should have asked if this can be done when the event is static. I edited my question to reflect that.
FYI, events can only be called inside the class its declared in.
So it will only delete the gameobject that's actually invoking the method, not the one that's subscribing to it?
Follow this Question
Related Questions
Subscribers of Delegates? 2 Answers
Delegates/Events across threads 0 Answers
Can you subscribe a delegate to an event? 2 Answers
How do Delegates and Events work? 1 Answer
Unity Events notifications 0 Answers