I’ve been using interfaces in my project when I use external services such as analytics, cloud and push notifications and its helped keep my project nice and modular.
I’m implementing push notifications now and would like my service to invoke a UnityEvent when it receives a push notification. The idea is that I would subscribe to the event from my manager script and it would work regardless of what service I use behind the scenes.
public interface IPushNotificationService
{
UnityEvent<PushNotificationObject> pushNotificationEvent;
void Initialize();
void PushNotificationHandler(string message, Dictionary<string, object> additionalData, bool isActive);
}
The error here is:
Assets/Scripts/PushNotifications/IPushNotificationService.cs(15,44): error CS0525: Interfaces cannot contain fields or constants
(for the UnityEvent line of code)
I could probably find another way around the problem, but I’m curious how one would solve this in C#.
For future reference: You can’t have fields in an interface, but you can have properties. Might not be the cleanest solution…
public interface IBlah {
UnityEvent thisEventHasToBeImplemented { get; }
}
public class Blah : IBlah {
UnityEvent _event = new UnityEvent();
UnityEvent thisEventHasToBeImplemented {
get { return _event; }
}
}
Sorry for closing my own post so soon, but my “workaround solution” was much cleaner than the original, so I’m going with that.
Instead of triggering events, I just pass an event handler to the initialize function.
public interface IPushNotificationService
{
void Initialize(Action<PushNotificationObject> notificationHandler);
}
I’m using OneSignal, so here’s my implementation (OneSignalService.cs):
#region IPushNotificationService implementation
public void Initialize (Action<PushNotificationObject> notificationHandler)
{
pushNotificationHandler = notificationHandler;
OneSignal.Init(appID, googleProjectNumber, HandleNotification);
}
#endregion
void HandleNotification (string message, System.Collections.Generic.Dictionary<string, object> additionalData, bool isActive)
{
string pushType = "";
if(additionalData.ContainsKey("Type"))
pushType = (string)additionalData["Type"];
PushNotificationObject pushObj = new PushNotificationObject();
pushObj.pushType = pushType;
pushObj.message = message;
pushObj.arguments = additionalData;
pushObj.isActive = isActive;
if (pushNotificationHandler != null)
pushNotificationHandler.Invoke (pushObj);
}