- Home /
This post has been wikified, any user with enough reputation can edit it.
Question by
just4unity · May 17, 2012 at 09:34 AM ·
eventsingleton
Best practice to use C# event on Singleton
Simple code first:
public class IUseEventFromSingleton : MonoBehaviour
{
void Start(){
MySingleton.instance.SomeEvent += OnSomeEvent;
}
void OnDestroy(){
MySingleton.instance.SomeEvent -= OnSomeEvent;
}
}
Sometimes there will be error like --> NullReferenceException: Object reference not set to an instance of an object.
MySingleton get destroyed before I remove SomeEvent!
I can get rid off this error by add if null check,then SomeEvent did not removed from that Singleton,am I right?
How you people handle this problem
Comment
Best Answer
Answer by BigBulle · May 17, 2012 at 09:51 AM
Yes I would add
if(MySingleton.instance!=null) MySingleton.instance.SomeEvent -= OnSomeEvent;
Thanks for your fast reply,I think this will memory leak,OnSomeEvent handler still there if $$anonymous$$ySingleton get destroyed before unsubscribe the event.I am not sure about the unity memory management,At least better than nothing.