Step-by-Step Unity 2.x to 3.0.0 Upgrade Guide

OneSignal Unity SDK 2.x.x to 3.x.x Migration Guide

Requirements

This guide assumes you are upgrading from a 2.x.x version of the OneSignal Unity SDK to the 3.x.x version. Additionally please ensure you are using:

  • Unity 2018.4 or newer
  • For iOS builds: CocoaPods 1.11.3 or newer

Adding 3.x.x to your project

Follow one of the following sections based on your previous install method of the OneSignal SDK.

Unity Package Manager

  1. If you have them delete the directory at Assets/OneSignal and the xml file at Assets/Plugins/Android/OneSignalConfig.plugin/AndroidManifest.xml
  2. In Unity open Window > Package Manager
  3. From the Package Manager window select Packages: in the top left and click on In Project
  4. Select the OneSignal Unity SDK(s) and press the Upgrade to 3.x.x button (make sure to update both Android and iOS packages)
  5. Follow the guides below for adding a Namespace and Updating method calls to fix any compilation errors
  6. Check the menu at Window > OneSignal SDK Setup to see if there are any remaining steps to run

Unity Asset Store

  1. Delete the directory at Assets/OneSignal and the xml file at Assets/Plugins/Android/OneSignalConfig.plugin/AndroidManifest.xml
  2. In Unity open Window > Package Manager
  3. From the Package Manager window select Packages: in the top left and click on My Assets
  4. Select the OneSignal SDK from the list and press the Update button.
  5. Once the update has completed click the Import button
  6. Navigate to Window > OneSignal SDK Setup
  7. Click Run All Steps
  8. Follow the guides below for adding a Namespace and Updating method calls to fix any compilation errors
  9. Navigate back to the menu at Window > OneSignal SDK Setup to see if there are any remaining steps to run

Unitypackage distributable

  1. Delete the directory at Assets/OneSignal and the xml file at Assets/Plugins/Android/OneSignalConfig.plugin/AndroidManifest.xml
  2. Download the latest release from our releases page
  3. In Unity navigate to Assets > Import Package > Custom Package... and select the newly downloaded *.unitypackage file
  4. Navigate to Window > OneSignal SDK Setup
  5. Click Run All Steps
  6. Follow the guides below for adding a Namespace and Updating method calls to fix any compilation errors
  7. Navigate back to the menu at Window > OneSignal SDK Setup to see if there are any remaining steps to run

Namespace

You will notice that previous uses of OneSignal no longer can be found. In any file you are using the OneSignal Unity SDK please add to the top of the file:

using OneSignalSDK;

Updating method calls

Added

SMS

A new feature of 3.x.x is the ability to manage a SMS subscription.

Set the user's SMS Number

OneSignal.Default.SetSMSNumber("+12345556789");

Set the user's SMS Number and get the result of the call

var result = await OneSignal.Default.SetSMSNumber("+12345556789");
if (result) {
    Debug.Log("success");
}
else {
    Debug.Log("error");
}

Unlink the SMS subscription from the device so that it will no longer be updated

OneSignal.Default.LogOutSMS();

Unlink the SMS subscription from the device so that it will no longer be updated and get the result of the call

var result = await OneSignal.Default.LogOutSMS();
if (result) {
    Debug.Log("success");
}
else {
    Debug.Log("error");
}

Get the current SMS subscription status

var smsState  = OneSignal.Default.SMSSubscriptionState;
var smsUserId = smsState.smsUserId;
var smsNumber = smsState.smsNumber;

Listen for SMS subscription status changes

OneSignal.Default.SMSSubscriptionStateChanged += (current, previous) => {
    var smsSubscribed = current.isSubscribed;
};

Updated

Initialization

2.x.x3.x.x
OneSignal.StartInit("your_app_id")
   .EndInit();
OneSignal.Default.Initialize("your_app_id");

We also now include a prefab for codeless initialization!

Located in the com.onesignal.unity.core package we've include a simple prefab which initializes OneSignal. You can easily find it using the Asset search bar to find OneSignalController.prefab and making sure to select All or In Packages for your search option. Drag the prefab into your very first scene, fill in the App Id, and you are immediately ready to go!

Debugging

Set the log and alert levels

2.x.x3.x.x
OneSignal.SetLogLevel(OneSignal.LOG_LEVEL.INFO, OneSignal.LOG_LEVEL.ERROR);
OneSignal.Default.LogLevel   = LogLevel.Info;
OneSignal.Default.AlertLevel = LogLevel.Error;

Privacy

Set whether user consent is required to start the SDK

2.x.x3.x.x
OneSignal.SetRequiresUserPrivacyConsent(true); // before init

// or

OneSignal.StartInit("your_app_id")
   .SetRequiresUserPrivacyConsent(true)
   .EndInit();
OneSignal.Default.RequiresPrivacyConsent = true; // before init

Set the status of the user's consent

2.x.x3.x.x
OneSignal.UserDidProvideConsent(true);
OneSignal.Default.PrivacyConsent = true;

Get the status of the user's consent

2.x.x3.x.x
if (OneSignal.UserProvidedConsent()) {
    // user provided consent
}
if (OneSignal.Default.PrivacyConsent) {
    // user provided consent
}

User Id

Set the external user id

2.x.x3.x.x
OneSignal.SetExternalUserId("3983ad1b-e31d-4df8-b063-85785ee34aa4");
OneSignal.Default.SetExternalUserId("3983ad1b-e31d-4df8-b063-85785ee34aa4");

Set the external user id and get the result of the call

2.x.x3.x.x
OneSignal.SetExternalUserId("3983ad1b-e31d-4df8-b063-85785ee34aa4",
    result => Debug.Log("success")
);
var result = await OneSignal.Default.SetExternalUserId("3983ad1b-e31d-4df8-b063-85785ee34aa4");
if (result) {
    Debug.Log("success");
}

Remove the external user id

2.x.x3.x.x
OneSignal.RemoveExternalUserId();
OneSignal.Default.RemoveExternalUserId();

Remove the external user id and get the result of the call

2.x.x3.x.x
OneSignal.RemoveExternalUserId(
    result => Debug.Log("success")
);
var result = await OneSignal.Default.RemoveExternalUserId();
if (result) {
    Debug.Log("success");
}

Push Notifications

Prompt the user for permission to send push notifications

2.x.x3.x.x
OneSignal.PromptForPushNotificationsWithUserResponse(response => {
    if (response) {
        // user accepted
    }
});
var response = await OneSignal.Default.PromptForPushNotificationsWithUserResponse();
if (response == NotificationPermission.Authorized) {
    // user accepted
}

Getting the current push notification permission status

2.x.x3.x.x
var currentDeviceState = OneSignal.GetPermissionSubscriptionState();
var currentStatus      = currentDeviceState.permissionStatus.status;

if (currentDeviceState.permissionStatus.hasPrompted == false) {
    // do if user was not prompted
}
var currentStatus = OneSignal.Default.NotificationPermission;
if (currentStatus == NotificationPermission.NotDetermined) {
    // do if user was not prompted
}

Listen for push notification permission status changes

2.x.x3.x.x
OneSignal.permissionObserver += changes => {
    var previousStatus = changes.from.status;
    var currentStatus  = changes.to.status;

    if (changes.to.hasPrompted) {
        // do if user was prompted
    }
};
OneSignal.Default.NotificationPermissionChanged += (current, previous) => {
    if (current != NotificationPermission.NotDetermined) {
        // do if user was prompted
    }
};

Get the current push notification subscription status

2.x.x3.x.x
var currentDeviceState = OneSignal.GetPermissionSubscriptionState();
var pushUserId         = currentDeviceState.subscriptionStatus.userId;
var pushIsSubscribed   = currentDeviceState.subscriptionStatus.subscribed;
var pushState        = OneSignal.Default.PushSubscriptionState;
var pushUserId       = pushState.userId;
var pushIsSubscribed = pushState.isSubscribed;

Listen for push notification subscription status changes

2.x.x3.x.x
OneSignal.subscriptionObserver += changes => {
    var prevPushState = changes.from;
    var currPushState = changes.to;

    var pushToken   = currPushState.pushToken;
    var pushEnabled = currPushState.userSubscriptionSetting;
};
OneSignal.Default.PushSubscriptionStateChanged += (current, previous) => {
    var pushToken   = current.pushToken;
    var pushEnabled = !current.isPushDisabled;
};

Disabling push notifications without removing the push subscription

2.x.x3.x.x
OneSignal.SetSubscription(false);
OneSignal.Default.PushEnabled = false;

Clear all OneSignal notifications from the notification shade

2.x.x3.x.x
OneSignal.ClearOneSignalNotifications();
OneSignal.Default.ClearOneSignalNotifications();

Get the push notification subscription status' ids

2.x.x3.x.x
OneSignal.IdsAvailable((pushUserId, pushToken) => {
    // perform action with push info
});
var pushUserId = OneSignal.Default.PushSubscriptionState.userId;
var pushToken  = OneSignal.Default.PushSubscriptionState.pushToken;

Sending a push to the user

2.x.x3.x.x
OneSignal.IdsAvailable((pushUserId, pushToken) => {
    var notification = new Dictionary<string, object> {
        ["contents"]           = new Dictionary<string, string> { ["en"] = "Test Message" },
        ["include_player_ids"] = new List<string> { pushUserId },
        ["send_after"]         = DateTime.Now.ToUniversalTime().AddSeconds(30).ToString("U")
    };

    OneSignal.PostNotification(notification,
        response => Debug.Log("success"),
        error => Debug.Log("error")
    );
});
var pushUserId = OneSignal.Default.PushSubscriptionState.userId;
var pushOptions = new Dictionary<string, object> {
    ["contents"]           = new Dictionary<string, string> { ["en"] = "Test Message" },
    ["include_player_ids"] = new List<string> { pushUserId },
    ["send_after"]         = DateTime.Now.ToUniversalTime().AddSeconds(30).ToString("U")
};

var result = await OneSignal.Default.PostNotification(pushOptions);
if (result != null) {
    Debug.Log("success");
}
else {
    Debug.Log("error");
}

In App Messages

Set a trigger value

2.x.x3.x.x
OneSignal.AddTrigger("triggerKey", 123);
OneSignal.Default.SetTrigger("triggerKey", 123);

Set several trigger values

2.x.x3.x.x
OneSignal.AddTriggers(new Dictionary<string, object> {
    ["trigger1"] = "abc",
    ["trigger2"] = 456
});
OneSignal.Default.SetTriggers(new Dictionary<string, object> {
    ["trigger1"] = "abc",
    ["trigger2"] = 456
});

Removing a trigger value

2.x.x3.x.x
OneSignal.RemoveTriggerForKey("trigger3");
OneSignal.Default.RemoveTrigger("trigger3");

Removing several trigger values

2.x.x3.x.x
OneSignal.RemoveTriggersForKeys(new[] { "trigger4", "trigger5" });
OneSignal.Default.RemoveTriggers(new[] { "trigger4", "trigger5" });

Pause In-App Messages

2.x.x3.x.x
OneSignal.PauseInAppMessages(true);
OneSignal.Default.InAppMessagesArePaused = true;

Email

Set the user's Email

2.x.x3.x.x
OneSignal.SetEmail("[email protected]");
OneSignal.Default.SetEmail("[email protected]");

Set the user's Email and get the result of the call

2.x.x3.x.x
OneSignal.SetEmail("[email protected]",
    () => Debug.Log("success"),
    error => Debug.Log("error")
);
var result = await OneSignal.Default.SetEmail("[email protected]");
if (result) {
    Debug.Log("success");
}
else {
    Debug.Log("error");
}

Unlink the Email subscription from the device so that it will no longer be updated

2.x.x3.x.x
OneSignal.LogoutEmail();
OneSignal.Default.LogoutEmail();

Unlink the Email subscription from the device so that it will no longer be updated and get the result of the call

2.x.x3.x.x
OneSignal.LogoutEmail(
    () => Debug.Log("success"),
    error => Debug.Log("error")
);
var result = await OneSignal.Default.LogoutEmail();
if (result) {
    Debug.Log("success");
}
else {
    Debug.Log("error");
}

Get the current Email subscription status

2.x.x3.x.x
var currentDeviceState = OneSignal.GetPermissionSubscriptionState();
var emailUserId        = currentDeviceState.emailSubscriptionStatus.emailUserId;
var emailAddress       = currentDeviceState.emailSubscriptionStatus.emailAddress;
var emailState = OneSignal.Default.EmailSubscriptionState;
var emailUserId  = emailState.emailUserId;
var emailAddress = emailState.emailAddress;

Listen for Email subscription status changes

2.x.x3.x.x
OneSignal.emailSubscriptionObserver += changes => {
    var prevEmailState = changes.from;
    var currEmailState = changes.to;

    var emailSubscribed = currEmailState.subscribed;
};
OneSignal.Default.EmailSubscriptionStateChanged += (current, previous) => {
    var emailSubscribed = current.isSubscribed;
};

Sync a hashed email

2.x.x3.x.x
OneSignal.SyncHashedEmail("[email protected]");
<b>REMOVED</b> - Please refer to our new Email methods/functionality such as setEmail()

Location

Set whether location sharing is enabled

2.x.x3.x.x
OneSignal.SetLocationShared(true);
OneSignal.Default.ShareLocation = true;

Prompt the user if they would like to share their location

2.x.x3.x.x
OneSignal.PromptLocation();
OneSignal.Default.PromptLocation();

Tags

Send a tag with a value

2.x.x3.x.x
OneSignal.SendTag("tagName", "tagValue");
OneSignal.Default.SendTag("tagName", "tagValue");

Send multiple tags with values

2.x.x3.x.x
OneSignal.SendTags(new Dictionary<string, string> {
    ["tag1"] = "123",
    ["tag2"] = "abc"
});
OneSignal.Default.SendTags(new Dictionary<string, string> {
    ["tag1"] = "123",
    ["tag2"] = "abc"
});

Get all tags

2.x.x3.x.x
OneSignal.GetTags(tags => {
    var tag3Value = tags["tag3"];
});
var tags = await OneSignal.Default.GetTags();
var tag3Value = tags["tag3"];

Delete a tag

2.x.x3.x.x
OneSignal.DeleteTag("tag4");
OneSignal.Default.DeleteTag("tag4");

Delete multiple tags

2.x.x3.x.x
OneSignal.DeleteTags(new[] { "tag5", "tag6" });
OneSignal.Default.DeleteTags(new[] { "tag5", "tag6" });

Outcomes

Send an outcome

2.x.x3.x.x
OneSignal.SendOutcome("outcomeName");
OneSignal.Default.SendOutcome("outcomeName");

Send a unique outcome

2.x.x3.x.x
OneSignal.SendUniqueOutcome("uniqueOutcomeName");
OneSignal.Default.SendUniqueOutcome("uniqueOutcomeName");

Send an outcome with a float value

2.x.x3.x.x
OneSignal.SendOutcomeWithValue("outcomeWithVal", 4.2f);
OneSignal.Default.SendOutcomeWithValue("outcomeWithVal", 4.2f);

Lifecycle

Previously setting up the callbacks for checking the 3 supported lifecycle methods had to be done exclusively during initialization. These are now available to be subscribed to at any time and several new lifecycle methods have been added.

Listen for when a push notification opened the app

2.x.x3.x.x
OneSignal.StartInit("your_app_id")
   .HandleNotificationOpened(onNotificationOpened)
   .EndInit();
   
void onNotificationOpened(OSNotificationOpenedResult result) {
    var notif = result.notification;
    var action = result.action;
}
OneSignal.Default.NotificationOpened += onNotificationOpened;

void onNotificationOpened(NotificationOpenedResult result) {
    var notif = result.notification;
    var action = result.action;
}

Listen for when a push notification is about to display while the app is in focus

2.x.x3.x.x
OneSignal.StartInit("your_app_id")
   .HandleNotificationReceived(onNotificationReceived)
   .EndInit();

void onNotificationReceived(OSNotification notification) {
    var notifID = notification.payload.notificationID;
}
OneSignal.Default.NotificationWillShow += onNotificationWillShow;

Notification onNotificationWillShow(Notification notification) {
    if (someCheck) {
        return null; // don't show the notificaiton
    }
    // COMING SOON - make modifications to the notification before showing
    return notification; // show the notification
}

Listen for when an action of an In-App Message was triggered by a button click

2.x.x3.x.x
OneSignal.StartInit("your_app_id")
   .HandleInAppMessageClicked(onIAMClicked)
   .EndInit();

void onIAMClicked(OSInAppMessageAction action) {
    var clickName = action.clickName;
}
OneSignal.Default.InAppMessageTriggeredAction += onIAMTriggedAction;

void onIAMTriggedAction(InAppMessageAction action) {
    var clickName  = action.clickName;
    var firstClick = action.firstClick;
}

Other

Set whether URLs embedded in push notification open within the app or in a browser

2.x.x3.x.x
OneSignal.StartInit("your_app_id")
   .Settings(new Dictionary<string, bool> { { OneSignal.kOSSettingsInAppLaunchURL, true } })
   .EndInit();
OneSignal.Default.SetLaunchURLsInApp(true);

Android - Background Notification Control

If you added native Android code to your app to handle notifications with the Notification Extender Service (NES) make sure to follow the
Background Notification Control part of the native Android migration guide.

  • Search for com.onesignal.NotificationExtender in your AndroidManifest.xml as an indicator if you set this up in the 2.x.x SDK.

Removed

Set whether or not push notifications show while the app is in focus

2.x.x3.x.x
OneSignal.inFocusDisplayType = OneSignal.OSInFocusDisplayOption.InAppAlert;

// or

OneSignal.StartInit("your_app_id")
   .InFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
   .EndInit();
Replaced by the feature of the NotificationWillShow event to determine if a notification will show or not.

Enable vibrate

2.x.x3.x.x
OneSignal.EnableVibrate(true);
REMOVED - Stopped working in Android 8+ due to a breaking change. To customize going forward, use Notification Categories (Channels).

Enable sound

2.x.x3.x.x
OneSignal.EnableSound(true);
REMOVED - Stopped working in Android 8+ due to a breaking change. To customize going forward, use Notification Categories (Channels).