Reputation: 1514
I have trouble figuring out how to remove listener for cloud function which is triggered every few minutes. I have the following code:
void InitializeFirebase() {
FirebaseDatabase.DefaultInstance.GetReference ("Main").ValueChanged += ListenForServerTimestamp;
}
void OnDisable() {
FirebaseDatabase.DefaultInstance.GetReference("Main").ValueChanged -= ListenForServerTimestamp;
}
The issue is that the even is still registered even when Unity is not running. Ie play button is turned off, it is still registering the events. I must be doing something wrong with removing the events, but after looking through all other answers, i cant figure out what is the issue.
Thanks.
Edit: If there is some way to disconnect Firebase in Unity, that would be also something i could try. But i cant again find anything anywhere on disconnecting Firebase in Unity.
Upvotes: 3
Views: 1147
Reputation: 3131
My top suggestion will be to cache your database reference in the script where you're retrieving it. Something like this:
DatabaseReference _mainRef;
void InitializeFirebase() {
_mainRef = FirebaseDatabase.DefaultInstance.GetReference ("Main");
_mainRef.ValueChanged += ListenForServerTimestamp;
}
void OnDisable() {
if(_mainRef != null) {
_mainRef.ValueChanged -= ListenForServerTimestamp;
_mainRef = null;
}
}
If you inspect GetReference
, you'll see something like this in ILSpy:
public DatabaseReference GetReference(string path)
{
return new DatabaseReference(this.internalDatabase.GetReference(path), this);
}
So you may be removing the listener on an object other than the one you register it on.
A few other things to double check. I'd recommend you do this on a MonoBehaviour
rather than a ScriptableObject
. Since you mention events getting triggered when the play button isn't selected, I expect that this is happening in Editor. ScriptableObject
generally doesn't behave the way I'd expect in Editor and can cause odd issues around play/pause.
If it is on a MonoBehaviour
, I would recommend that you not place it on one that has the [ExecuteInEditMode]
attribute. You can also get odd behavior if you're invoking some of these calls from an Editor script (CustomEditor, PropertyDrawer, &c).
I don't think any of these (other than the ref) are your issue. But it's a few more things to look at.
I hope this helps!
--Patrick
Upvotes: 2