Unity SDK

OneSignal Unity SDK Reference.
Works with iOS, Android, Amazon.

📘

Just starting with Unity?

Check out our Unity SDK Setup guide.

ParameterData TypeDescription
Debugging
setLogLevelMethodEnable logging to help debug OneSignal implementation.
Initialization
StartInitMethodStarts initialization of OneSignal, call this on Start method of the first scene that loads. See Unity SDK Setup for details and code examples.
inFocusDisplayingMethodSetting to control how OneSignal notifications will be shown when one is received while your app is in focus.
SettingsMethodiOS - Automatically Prompt Users to Enable Notifications and Open all URLs in In-App Safari Window
EndInitMethodMust be called after StartInit to complete initialization of OneSignal.
Handling Notifications
NotificationReceivedMethodAdds an observer function/callback that will get executed whenever a new OneSignal push notification is received on the device when app is in the foreground.
NotificationOpenedMethodWhen a user takes an action on a notification
Privacy
setRequiresUserPrivacyConsentMethodDelays initialization of the SDK until the user provides privacy consent
UserDidProvideConsentMethodAndroid, iOS - Provides privacy consent
iOS Prompting
promptForPushNotificationsWithUserResponseMethodPrompt the user for notification permissions. Callback fires as soon as the user accepts or declines notifications.

Must set kOSSettingsKeyAutoPrompt to false when calling initWithLaunchOptions.

Recommended: Set to false and follow iOS Push Opt-In Prompt.
User Status
getPermissionSubscriptionStateMethodGet the current notification and permission state. Returns a OSPermissionSubscriptionState type.
addPermissionObserverEvent DelegatePermission status changes
addSubscriptionObserverEvent DelegateSubscription status changes
setSubscriptionMethodDisable OneSignal from sending notifications to current device.
External User IDs
setExternalUserIdMethodAllows you to use your own system's user ID's to send push notifications to your users. To tie a user to a given user ID, you can use this method.
removeExternalUserIdMethodRemoves whatever was set as the current user's external user ID.
Tagging
getTagsMethodView Tags from current device record.
sendTagMethodAdd a single Data Tag to current device record.
sendTagsMethodAdd multiple Data Tags to current device record.
deleteTagMethodDelete a Tag from current device record.
deleteTagsMethodDelete multiple Tags from current device record.
Location Data
setLocationSharedMethodDisable or Enable SDK location collection. See Handling Personal Data.
promptLocationMethodPrompt Users for Location Not Recommended

Recommended: Use In-App Message Location Opt-In Prompt.
Sending Notifications
postNotificationMethodSend or schedule a notification to a OneSignal Player ID.
cancelNotificationMethodDelete a single app notification
clearOneSignalNotificationsMethodDelete all app notifications
In-App Messaging - Link
addTriggerMethodAdd a trigger, may show an In-App Message if its triggers conditions were met.
addTriggersMethodAdd a map of triggers, may show an In-App Message if its triggers conditions were met.
removeTriggerForKeyMethodRemoves a list of triggers based on a collection of keys, may show an In-App Message if its triggers conditions were met.
getTriggerValueForKeyMethodGets a trigger value for a provided trigger key.
pauseInAppMessagesMethodAllows you to temporarily pause all In App Messages.
setInAppMessageClickHandlerMethodSets an In App Message opened block
Email
setEmailMethodSet user's email. Creates a new user record for the email address. Use sendTag if you want to update a push user record with the email.
logoutEmailMethodLog user out to dissociate email from device
addEmailSubscriptionObserverMethodObserver for subscription changes to email
Notification Objects
OSNotificationOpenedResultClassInformation returned from a notification the user received.
OSNotificationClassRepresents a received push notification
OSNotificationActionClassHow user opened notification
OSNotificationPayloadClassData that comes with a notification
Appearance
enableVibrateMethodAndroid - When user receives notification, vibrate device less
enableSoundMethodAndroid - When user receives notification, do not play a sound

Initialization

Settings

Method

Settings that can be passed into the initialization chaining method.

Settings key options are:

  • OneSignal.kOSSettingsAutoPrompt - Auto prompt user for notification permissions.
  • OneSignal.kOSSettingsInAppLaunchURL - Launch notifications with a launch URL as an in app webview.
ParameterTypeDescription
settingsDictionary<string, bool>Additional initialization settings. Set true or false.

Privacy

SetRequiresUserPrivacyConsent

Method

Allows you to delay the initialization of the SDK until the user provides privacy consent. The SDK will not be fully initialized until the UserDidProvideConsent(true) method is called. The SDK will remember the answer to the last time UserDidProvideConsent was called so you only need to call it once.

If you set this to be true, the SDK will not fully initialize until consent is provided. You can still call OneSignal methods, but nothing will happen, and the user will not be registered for push notifications.

void YourAppInitMethod() {
  // SetRequiresUserPrivacyConsent will prevent
  //   initialization until UserDidProvideConsent(true) is called
  OneSignal.StartInit("YOUR_APP_ID")
    .SetRequiresUserPrivacyConsent(true)
    .EndInit();
}

UserDidProvideConsent

Method

If your application is set to require the user's privacy consent, you can provide this consent using this method. Until you call UserDidProvideConsent(true), the SDK will not fully initialize and will not send any data to OneSignal. The SDK will remember the answer to the last time UserDidProvideConsent was called so you only need to call it once.

void UserAcceptedConsent() {
   // Only needs to be called once,
   //   OneSignal will remember the last answer 
   OneSignal.UserDidProvideConsent(true);
}

UserProvidedConsent

Method

Returns a boolean indicating if the user has given privacy consent yet.

Prompting

PromptForPushNotificationsWithUserResponse

Method - iOS

Call this when you would like to prompt an iOS user to accept push notifications with the default system prompt. Only use if you passed false to autoRegister when calling Init.

OneSignal.PromptForPushNotificationsWithUserResponse(OneSignal_promptForPushNotificationsReponse);

private void OneSignal_promptForPushNotificationsReponse(bool accepted) {
  Debug.Log("OneSignal_promptForPushNotificationsReponse: " + accepted);
}

Status

GetPermissionSubscriptionState

Method

Get the current notification and permission state. Returns a OSPermissionSubscriptionState type described below.

permissionStatusOSPermissionStateDevice's Notification Permissions state
subscriptionStatusOSSubscriptionStatePush Protocol and OneSignal subscription state
var status = OneSignal.GetPermissionSubscriptionState();
status.permissionStatus.hasPrompted;
status.permissionStatus.status;

status.subscriptionStatus.subscribed;
status.subscriptionStatus.userSubscriptionSetting;
status.subscriptionStatus.userId;
status.subscriptionStatus.pushToken;

permissionObserver

Event Delegate

Delegate will be fired when a notification permission setting changes.
This includes the following events:

  • Notification permission prompt shown. iOS
  • The user accepting or declining the permission prompt iOS
  • Enabling/disabling notifications for your app in the Device's Settings after returning to your app.

Example

Output is showings the user accepting the notification permission prompt.

OneSignal.permissionObserver += OneSignal_permissionObserver;

 private void OneSignal_permissionObserver(OSPermissionStateChanges stateChanges) {
       // Example of detecting anwsering the permission prompt
    if (stateChanges.from.status == OSNotificationPermission.NotDetermined) {
      if (stateChanges.to.status == OSNotificationPermission.Authorized)
         Debug.Log("Thanks for accepting notifications!");
      else if (stateChanges.to.status == OSNotificationPermission.Denied)
         Debug.Log("Notifications not accepted. You can turn them on later under your device settings.");
    }
   
    Debug.Log("stateChanges.to.status: " + stateChanges.to.status);
 }

subscriptionObserver

Event Delegate

Delegate will be fired when a notification subscription property changes.

This includes the following events:

  • Getting a push token from Apple or Google.
  • Getting a player / user id from OneSignal
  • OneSignal.setSubscription is called
  • User disables or enables notifications

Example

OneSignal.subscriptionObserver += OneSignal_subscriptionObserver;

private void OneSignal_subscriptionObserver(OSSubscriptionStateChanges stateChanges) {
      Debug.Log("stateChanges: " + stateChanges);
      Debug.Log("stateChanges.to.userId: " + stateChanges.to.userId);
      Debug.Log("stateChanges.to.subscribed: " + stateChanges.to.subscribed);
   }

Tags

GetTags

Method

Retrieve a list of tags that have been set on the player from the OneSignal server.

ParameterTypeDescription
inTagsReceivedDelegateTagsReceivedDelegate gets called once the tags are available.
void SomeMethod() {
        OneSignal.GetTags(TagsReceived);
    }

    private void TagsReceived(Dictionary<string, object> tags) {
        foreach (var tag in tags)
            print(tag.Key + ":" + tag.Value);
    }

TagsReceived

Delegate

Delegate you can define to get the all the tags set on a player from onesignal.com.

ParameterTypeDescription
tagsDictionary<string, object>Dictionary of key value pairs retrieved from the OneSignal server.
private static void TagsReceived(Dictionary<string, object> tags) {
        foreach (var tag in tags)
            print(tag.Key + ":" + tag.Value);
    }

SendTag

Method

Tag a player based on a game event of your choosing so later you can create segments on onesignal.com to target these players. If you need to set more than one key at a time please use SendTags instead.

ParameterTypeDescription
keyStringKey of your choosing to create or update.
valueStringValue to set on the key. NOTE: Passing in a blank String deletes the key, you can also call DeleteTag or DeleteTags.
OneSignal.SendTag("key", "value");

SendTags

Method

Set multiple tags on a player with one call.

ParameterTypeDescription
tagsDictionary<string, string>An IDictionary of key value pairs. NOTE: Passing in a blank as a value deletes the key, you can also call DeleteTag or DeleteTags.
OneSignal.SendTags(new Dictionary<string, string>() { {"UnityTestKey2", "value2"}, {"UnityTestKey3", "value3"} });

DeleteTag

Method

Deletes a tag that was previously set on a player with SendTag or SendTags. Please use DeleteTags if you need to delete more than one tag.

ParameterTypeDescription
keyStringKey to remove.
OneSignal.DeleteTag("key");

DeleteTags

Method

Deletes tags that were previously set on a player with SendTag or SendTags.

ParameterTypeDescription
keysIListKeys to remove.
OneSignal.DeleteTags(new List<string>() {"UnityTestKey2", "UnityTestKey3" })

Data

PromptLocation

Method

Prompts the user for location permissions. This allows for geotagging so you can send notifications to users based on location.

OneSignal.PromptLocation();
iOS INSTRUCTIONS

You must add all of the following to your iOS plist settings:

NSLocationUsageDescription

NSLocationWhenInUseUsageDescription

ANDROID INSTRUCTIONS

You must add one of the following Android Permissions:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

SetLocationShared

Method

Accepts a boolean parameter, allows you to enable or disable OneSignal SDK location tracking. Please note that if you disable location tracking, you will not be able to use location based push notifications.

//disables location features
OneSignal.SetLocationShared(false);

Receiving Notifications

PostNotification

Allows you to send notifications from user to user or schedule ones in the future to be delivered to the current device or specific player ids.

ParameterTypeDescription
parametersDictionary<string, object>Dictionary of notification options, see our Create notification POST call for all options.
ReturnsMethod
onSuccessOnPostNotificationSuccess delegate fires when the notification was created on OneSignal's server.

Dictionary<string, object> - Json response from OneSignal's server.

This will contain an "id" you can later use to cancel if was scheduled in the future.
onFailureOnPostNotificationFailure delegate fires when the notification failed to create

Dictionary<string, object> - Json response from OneSignal's server.
using OneSignalPush.MiniJSON;

private static string oneSignalDebugMessage;

void someMethod() {
  // Just an example userId, use your own or get it the devices by using the GetPermissionSubscriptionState method
  string userId = "b2f7f966-d8cc-11e4-bed1-df8f05be55ba";

  var notification = new Dictionary<string, object>();
  notification["contents"] = new Dictionary<string, string>() { {"en", "Test Message"} };

  notification["include_player_ids"] = new List<string>() { userId };
  // Example of scheduling a notification in the future.
  notification["send_after"] = System.DateTime.Now.ToUniversalTime().AddSeconds(30).ToString("U");

  OneSignal.PostNotification(notification, (responseSuccess) => {
    oneSignalDebugMessage = "Notification posted successful with id: " + responseSuccess["id"];
  }, (responseFailure) => {
    oneSignalDebugMessage = "Notification failed to post:\n" + Json.Serialize(responseFailure);
  });


}

See the Create notification REST API POST call for a list of all possible options. Note: You can only use include_player_ids as a targeting parameter from your app. Other target options such as tags and included_segments require your OneSignal App REST API key which can only be used from your server.

Canceling a Notification

After creating the notification using postNotification you can save the notification "id" from the responseSuccess callback to use for canceling the push if required.

Using the API Cancel notification endpoint, you can use something like this to cancel that push if needed through the SDK.

string url = "https://onesignal.com/api/v1/notifications/" + notificationId.ToString() + "?app_id=" + appId;

WebRequest request = WebRequest.Create(url);
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
request.Method = "DELETE";
request.GetResponse();

ClearOneSignalNotifications

Removes all OneSignal app notifications from the Notification Shade.

OneSignal.ClearOneSignalNotifications();

SetSubscription

Method

You can call this method with false to opt users out of receiving all notifications through OneSignal. You can pass true later to opt users back into notifications.

ParameterType
enableBoolean
OneSignal.SetSubscription(false);

setEmail

Method

setEmail allows you to set the user's email address with the OneSignal SDK. We offer several overloaded versions of this method.

OneSignal.SetEmail("[email protected]");

If you have a backend server, we strongly recommend using Identity Verification with your users. Your backend can generate an email authentication token and send it to your app. The following code also includes callbacks:

string emailAuthToken = ""; //from your backend server

OneSignal.SetEmail("[email protected]", emailAuthToken, () => {
    //Successfully set email
}, (error) => {
    //Encountered error setting email
});

logoutEmail

Method

If your app implements logout functionality, you can call logoutEmail to dissociate the email from the device:

OneSignal.LogoutEmail (() => {
    // Successfully logged out of email
}, (error) => {
    // Encountered error logging out of email
});

addEmailSubscriptionObserver

Method

We have also added a new email subscription observer to track changes to email subscriptions (ie. the user sets their email or logs out). In order to subscribe to email subscription changes you can implement the following:

void Start() {
    OneSignal.emailSubscriptionObserver += OneSignal_emailSubscriptionObserver;
}

Now, whenever the email subscription changes, this method will be called:

private void OneSignal_emailSubscriptionObserver(OSEmailSubscriptionStateChanges stateChanges) {
    string newEmailAddress = stateChanges.to.emailAddress;
}

External ID's

setExternalUserId

Method

If your system assigns unique identifiers to users, it can be annoying to have to also remember their OneSignal user ID's as well. To make things easier, OneSignal now allows you to set an external_id for your users. Simply call this method, pass in your custom user ID (as a string), and from now on when you send a push notification, you can use include_external_user_ids instead of include_player_ids.

string myCustomUniqueUserId = "something from my backend server";
  
OneSignal.SetExternalUserId(myCustomUniqueUserId);

removeExternalUserId

Method

If your user logs out of your app and you would like to disassociate their custom user ID from your system with their OneSignal user ID, you will want to call this method.

//usually called after the user logs out of your app
OneSignal.RemoveExternalUserId();

Notification Events

NotificationReceived

Method

Use to process a OneSignal notification that was just received while the app was in focus.

ParameterTypeDescription
resultOSNotificationObject containing properties of the notification.
OneSignal.StartInit("b2f7f966-d8cc-11e4-bed1-df8f05be55ba")
  .HandleNotificationReceived(HandleNotificationReceived)
  .EndInit();

// Called when your app is in focus and a notificaiton is recieved.
// The name of the method can be anything as long as the signature matches.
// Method must be static or this object should be marked as DontDestroyOnLoad
private static void HandleNotificationReceived(OSNotification notification) {
  OSNotificationPayload payload = notification.payload;
  string message = payload.body;

  print("GameControllerExample:HandleNotificationReceived: " + message);
  print("displayType: " + notification.displayType);
  extraMessage = "Notification received with text: " + message;
}

NotificationOpened

Method

Use to process a OneSignal notification the user just tapped on.

ParameterTypeDescription
resultOSNotificationOpenedResultObject containing both the user's response and properties of the notification.
OneSignal.StartInit("b2f7f966-d8cc-11e4-bed1-df8f05be55ba")
  .HandleNotificationOpened(HandleNotificationOpened)
  .EndInit();

// Called when a notification is opened.
// The name of the method can be anything as long as the signature matches.
// Method must be static or this object should be marked as DontDestroyOnLoad
private static void HandleNotificationOpened(OSNotificationOpenedResult result) {
  OSNotificationPayload payload = result.notification.payload;
  Dictionary<string, string> additionalData = payload.additionalData;
  string message = payload.body;
  string actionID = result.action.actionID;
  
  print("GameControllerExample:HandleNotificationOpened: " + message);
  extraMessage = "Notification opened with text: " + message;

  if (additionalData != null) {
    if (additionalData.ContainsKey("discount")) {
      extraMessage = (string)additionalData["discount"];
      // Take user to your store.
    }
  }
  if (actionID != null) {
    // actionSelected equals the id on the button the user pressed.
    // actionSelected will equal "__DEFAULT__" when the notification itself was tapped when buttons were present.
    extraMessage = "Pressed ButtonId: " + actionID;
  }
}

OSNotificationOpenedResult

Class

The information returned from a notification the user received.

ParameterTypeDescription
notificationOSNotificationNotification the user opened.
actionOSNotificationActionThe action the user took on the notification.

OSNotification

Class

The notification the user opened.

ParameterTypeDescription
isAppInFocusbooleanWas app in focus.
shownbooleanWas notification shown to the user. Will be false for silent notifications.
androidNotificationIdintAndroid Notification assigned to the notification. Can be used to cancel or replace the notification.
payloadOSNotificationPayloadPayload received from OneSignal.
displayTypeDisplayTypeHow the notification was displayed to the user.
groupedNotificationsList<OSNotificationPayload>Notification is a summary notification for a group this will contain all notification payloads it was created from.

displayType

Object

How the notification was displayed to the user. Part of OSNotification. See InFocusDisplaying for more information on how this is used.

Notification - native notification display.
InAppAlert (Default) - native alert dialog display.
None - notification is silent, or InFocusDisplaying is disabled.

OSNotificationAction

Class

The action the user took on the notification.

ParameterTypeDescription
typeActionTypeWas the notification opened normally (Opened) or was a button pressed on the notification (ActionTaken).
actionIDStringIf type == ActionTaken then this will contain the id of the button pressed.

OSNotificationPayload

Class

Contents and settings of the notification the user received.

ParameterTypeDescription
notificationIdStringOneSignal notification UUID.
titleStringTitle of the notification.
bodyStringBody of the notification.
additionalDataJSONObjectCustom additional data that was sent with the notification. Set on the dashboard under Options > Additional Data or with the 'data' field on the REST API.
smallIconStringSmall icon resource name set on the notification.
largeIconStringLarge icon set on the notification.
bigPictureStringBig picture image set on the notification.
smallIconAccentColorStringAccent color shown around small notification icon on Android 5+ devices. ARGB format.
launchUrlStringURL to open when opening the notification.
soundStringSound resource to play when the notification is shown.
ledColorStringDevices that have a notification LED will blink in this color. ARGB format.
lockScreenVisibilityintPrivacy setting for how the notification should be shown on the lockscreen of Android 5+ devices. 1 = Public (fully visible)(default), 0 = Private (Contents are hidden), -1 = Secret (not shown).
groupKeyStringNotifications with this same key will be grouped together as a single summary notification.
groupMessagestringSummary text displayed in the summary notification.
actionButtonsList<ActionButton>List of action buttons on the notification.
fromProjectNumberStringThe Google project number the notification was sent under.
backgroundImageLayoutBackgroundImageLayoutIf a background image was set this object will be available.
rawPayloadStringRaw JSON payload string received from OneSignal.

ActionButton

Object

List of action buttons on the notification. Part of OSNotificationPayload.

ParameterTypeDescription
idStringId assigned to the button.
textStringText show on the button to the user.
iconStringIcon shown on the button.

BackgroundImageLayout

Object - Android

If a background image was set, this object will be available. Part of OSNotificationPayload.

ParameterTypeDescription
imageStringImage URL or name used as the background image.
titleTextColorStringText color of the title on the notification. ARGB Format.
bodyTextColorStringText color of the body on the notification. ARGB Format.

Appearance

EnableVibrate

Method - Android

By default OneSignal always vibrates the device when a notification is displayed unless the device is in a total silent mode. Passing false means that the device will only vibrate lightly when the device is in it's vibrate only mode.

You can link this action to a UI button to give your user a vibration option for your notifications.

OneSignal.EnableVibrate(false);

EnableSound

Method - Android

By default OneSignal plays the system's default notification sound when the device's notification system volume is turned on. Passing false means that the device will only vibrate unless the device is set to a total silent mode.

You can link this action to a UI button to give your user a different sound option for your notifications.

OneSignal.EnableSound(false);

In-App Messaging

See Sending In-App Messages before getting started.

How do triggers work?

In-App Message triggers are handled by our SDK using the addTrigger or addTriggers method. A trigger is a key: value pair of string or integer data that you set programmatically in your app when an event occurs.

For example, if you want to send an IAM when a user reaches level 5 and level 10 of your game. Each time the use grows a level, you would call for example OneSignal.addTrigger("level", 1); then when they reach level 2, you simply update the trigger OneSignal.addTrigger("level", 2); and so on. At OneSignal.addTrigger("level", 5); you can then have the IAM show to the user by setting the key as level is 5 or level is greater than or equal to 5

Triggers are cleared each time the app is closed.

addTrigger

Method

Add a trigger, may show an In-App Message if its triggers conditions were met.

ParameterTypeDescription
keyStringKey for the trigger
valueObject (String or Number Recommended)Value of the trigger.
Object passed in will have toString()called if not a String

Example

// Add a single trigger
OneSignal.AddTrigger("key", "value");

addTriggers

Method

Add a map of triggers, may show an In-App Message if its triggers conditions were met.

ParameterTypeDescription
triggersMap<String, Object>Allows you to set multiple trigger key/value pairs simultaneously.

removeTriggerForKey

Method

Removes a single trigger for the given key, may show an In-App Message if its triggers conditions were met.

Example

ParameterTypeDescription
keyStringKey for trigger remove
// Delete a trigger
OneSignal.RemoveTriggerForKey("key");

removeTriggersForKeys

Method

Removes a list of triggers based on a collection of keys, may show an In-App Message if its triggers conditions were met.

ParameterTypeDescription
keysCollection<String>Removes a collection of triggers from their keys

getTriggerValueForKey

Method

Gets a trigger value for a provided trigger key.

ParameterTypeDescription
keyStringReturns a single trigger value for the given key,
if it exists, otherwise returns null
Return Type
StringValue if added with addTrigger or null if never set.

Example

// Get the current value to a trigger by key
var triggerValue = OneSignal.GetTriggerValueForKey("key");

pauseInAppMessages

Method

Allows you to temporarily pause all In App Messages. You may want to do this while the user is watching a video playing a match in your game to make sure they don't get interrupted at a bad time.

ParameterTypeDescription
pausebooleanTo pause set true
To resume set false

HandleInAppMessageClicked

Builder Method

Sets a In App Message opened handler. The instance will be called when an In App Message action is tapped on.

ParameterTypeDescription
handlerInAppMessageClicked Instance to a class implementing this interference.

Example

OneSignal.StartInit("YOUR_ONESIGNAL_APP_ID")
               .HandleInAppMessageClicked(HandleInAppMessageClicked)
               .EndInit();

InAppMessageClickHandler

Handler

Use to process an In App Message the user just tapped on.

ParameterTypeDescription
resultOSInAppMessageAction Details about the In App Message action element (button or image) that was tapped on.

Example

public static void HandleInAppMessageClicked(OSInAppMessageAction action) {
    String logInAppClickEvent = "In-App Message opened with action.clickName " + action.clickName;
    print(logInAppClickEvent);
    extraMessage = logInAppClickEvent;
}

OSInAppMessageAction

Class

Details about the In App Message action element (button or image) that was tapped on.

FieldTypeDescription
clickNameStringAn optional click name defined for the action element.
null if not set
clickUrlStringAn optional URL that opens when the action takes place.
null if not set.
firstClickbooleantrue if this is the first time the user has pressed
any action on the In App Message.
closesMessagebooleanDid the action close the In App Message.
true - In App Message will animate off the screen.
false - In App Message will stay on screen until the user dismisses.