Pular para o conteúdo principal

Visão geral

Configurando notificações push para seu app Unity usando OneSignal

Integrar notificações push ao seu app Unity é uma maneira poderosa de aumentar o engajamento e retenção de usuários. O Unity SDK do OneSignal suporta dispositivos iOS (APNS), Android (FCM), Amazon (ADM) e Huawei, permitindo mensagens em tempo real com esforço mínimo. Seja construindo jogos móveis ou apps interativos, este guia ajuda você a integrar o OneSignal de forma rápida e confiável.

Requisitos

  • Unity 2022.3 ou mais recente
  • App e plataforma OneSignal configurados
Requisitos iOS
  • macOS com Xcode 14+ (instruções de configuração usam Xcode 16.2)
  • Dispositivo com iOS 12+, iPadOS 12+, ou simulador Xcode rodando iOS 16.2+
Requisitos Android
  • Dispositivo ou emulador Android 7.0+ com Google Play Store (Services) instalado

Configure your OneSignal app and platform

Configure your OneSignal app with the platforms you support — Apple (APNs), Google (FCM), Huawei (HMS), and/or Amazon (ADM).
If your organization already has a OneSignal account, ask to be invited to the Organization. Otherwise, sign up for a free account to get started.
1

Create or select your app

Create a new app by clicking New App/Website, or add a platform to an existing app in Settings > Push & In-App. Select the platform(s) you want to configure and click Next: Configure Your Platform.
OneSignal dashboard showing the new app setup flow with Organization name, app name, and channel selection

Setting up your first OneSignal app, Organization, and channel.

2

Configure platform credentials

Enter the credentials for your platform:Click Save & Continue after entering your credentials.
3

Save your App ID and install the SDK

Your App ID is displayed on the final screen. Copy and save it — you need it when initializing the SDK. Select your SDK platform, then follow the setup guide.
OneSignal dashboard showing the App ID and team invite option after setup

Save your App ID and invite additional team members.


Configuração

1. Adicionar o OneSignal Unity SDK

Dois métodos de instalação estão disponíveis:
  1. Adicione o SDK à sua conta via Add to My Assets.
  2. Clique em Open in Unity para abrir o Unity Editor e Package Manager.
  3. Baixe e Importe o SDK.

OneSignal Unity SDK em My Assets

  1. Aceite o prompt para importar todos os arquivos.
  2. Vá para Window > OneSignal SDK Setup e siga a checklist, especialmente Import OneSignal packages.
  3. Após importar, Unity atualizará o registro. Complete os passos de configuração restantes mostrados na janela de setup.

Janela OneSignal SDK Setup

2. Configuração de plataforma

Adicione todas as plataformas que seu app suporta.

Configuração iOS

Nosso SDK auto-configura as configurações Xcode necessárias. Escolha sua abordagem de provisionamento:
  1. Vá para File > Build Settings > Player Settings.
  2. Em Other Settings, marque Automatically Sign.

Habilitar assinatura automática no Unity

Configuração Android

  1. Vá para Edit > Project Settings > Player > Android.
  2. Em Publishing Settings, habilite:
  • Custom Main Gradle Template
  • Custom Gradle Properties Template
  1. Execute Assets > External Dependency Manager > Android Resolver > Force Resolve.
Considerações adicionais:
  • Target API Level deve ser 33+ (v5.0.6+).
  • Se Minify estiver habilitado, execute Copy Android plugin to Assets de OneSignal SDK Setup para usar OneSignalConfig.androidlib.
  • Substitua os ícones padrão dentro de Assets/Plugins/Android/OneSignalConfig.androidlib/src/main/res pelos seus próprios (apenas nomes de arquivo em minúsculas, sublinhados permitidos). Veja Customize Notification Icons para mais.

Configuração Amazon

Apenas necessário para apps Amazon disponíveis via Amazon App Store.
  1. Edite ou crie Plugins/Android/AndroidManifest.xml.
  2. Adicione namespace:
  1. Adicione permissões:
  1. Adicione o seguinte à tag <application>:
  1. Substitua todas as instâncias de COM.YOUR.PACKAGE_NAME pelo seu nome de pacote real.
  2. Coloque seu api_key.txt em Assets/Plugins/Android/OneSignalConfig.androidlib/src/main/assets

Configuração Huawei

Apenas necessário para apps Huawei disponíveis via Huawei App Gallery.Veja Configuração Huawei Unity SDK para mais.

Opcional: Desabilitar o módulo de localização

A partir do OneSignal Unity SDK 5.3.0, você pode excluir o módulo de localização nativo do OneSignal das compilações iOS e Android quando seu app não usa OneSignal.Location. Por padrão, o SDK inclui o módulo de localização nativo para que as APIs de localização funcionem sem configuração adicional. Defina o indicador antes de resolver as dependências do Android ou compilar o iOS. Há duas formas de excluí-lo:
  • Alternância do Editor (interativa): No Unity Editor, vá para Project Settings > OneSignal e habilite Disable Location Module. A configuração é salva em ProjectSettings/OneSignalSettings.json.
  • Variável de ambiente (CLI/CI): Exporte ONESIGNAL_DISABLE_LOCATION=true (ou 1) no shell antes de iniciar o Unity. A variável de ambiente tem precedência sobre a alternância do Editor.
Quando o módulo de localização está desabilitado, o SDK grava dependências nativas granulares em Assets/OneSignal/Editor/OneSignalAndroidDependencies.xml e Assets/OneSignal/Editor/OneSignaliOSDependencies.xml. Depois de executar Assets > External Dependency Manager > Android Resolver > Force Resolve, o Android resolve os módulos OneSignal sem o artefato de localização em Assets/Plugins/Android/mainTemplate.gradle. As compilações iOS usam pods OneSignal sem OneSignalLocation. OneSignal.Location.RequestPermission() e atribuir OneSignal.Location.IsShared não executam nenhuma ação em compilações nativas sem o módulo de localização. OneSignal.Location.IsShared retorna false.

Aplicar a alteração após as dependências nativas serem armazenadas em cache

Se você alternar essa configuração em um projeto existente, limpe as saídas nativas obsoletas e resolva novamente as dependências com o indicador definido:
  • Exclua Assets/OneSignal/Editor/OneSignalAndroidDependencies.xml e Assets/OneSignal/Editor/OneSignaliOSDependencies.xml, depois reabra o projeto para que o Unity os regenere a partir de ProjectSettings/OneSignalSettings.json.
  • Execute Assets > External Dependency Manager > Android Resolver > Force Resolve para que Assets/Plugins/Android/mainTemplate.gradle receba os pacotes sem localização.
  • Reexporte o projeto Xcode do iOS e execute pod install, se necessário.
  • Remova Build/ e outras saídas geradas antes de recompilar.
Na CI, exporte ONESIGNAL_DISABLE_LOCATION no mesmo ambiente que inicia o Unity. Inclua o valor do indicador nas chaves de cache do Unity Library/, Gradle, CocoaPods e DerivedData para que um cache restaurado não traga de volta o módulo de localização.

3. Inicializar o SDK

Adicione este código dentro do método Start() de um MonoBehaviour no início do ciclo de vida da sua aplicação. Substitua YOUR_APP_ID pelo seu OneSignal App ID encontrado no seu dashboard OneSignal Settings > Keys & IDs.
Se você não tem acesso ao app OneSignal, peça aos seus Team Members para convidá-lo.
C#

Testing the OneSignal SDK integration

This guide helps you verify that your OneSignal SDK integration is working correctly by testing push notifications, subscription registration, and in-app messaging.
If you are testing with an Android emulator, it should start with a cold boot.
  1. Go to Device Manager in Android Studio.
  2. Select your emulator device and click Edit.
  3. Go to Additional Settings or More.
  4. Set the Boot option to Cold Boot.
  5. Save changes and restart the emulator.

Check mobile subscriptions

1

Launch your app on a test device.

The native push permission prompt should appear automatically if you added the requestPermission method during initialization.

iOS and Android push permission prompts

2

Check your OneSignal dashboard

Before accepting the prompt, check the OneSignal dashboard:
  • Go to Audience > Subscriptions.
  • You should see a new entry with the status “Never Subscribed”.

Dashboard showing subscription with 'Never Subscribed' status

3

Return to the app and tap Allow on the prompt.

4

Refresh the OneSignal dashboard Subscription's page.

The subscription’s status should now show Subscribed.

Dashboard showing subscription with 'Subscribed' status

You have successfully created a mobile subscription. Mobile subscriptions are created when users first open your app on a device or if they uninstall and reinstall your app on the same device.

Set up test users

test users are helpful for testing a push notification before sending a message.
1

Add to Test Users.

In the dashboard, next to the subscription, click the Options (three dots) button and select Add to Test Users.

Adding a device to Test Users

2

Name your subscription.

Name the subscription so you can easily identify your device later in the test users tab.
3

Create a test users segment.

Go to Audience > Segments > New Segment.
4

Name the segment.

Name the segment Test Users (the name is important because it will be used later).
5

Add the Test Users filter and click Create Segment.

Creating a 'Test Users' segment with the Test Users filter

You have successfully created a segment of test users. We can now test sending messages to this individual device and groups of test users.

Send test push via API

1

Get your App API Key and App ID.

In your OneSignal dashboard, go to Settings > Keys & IDs.
2

Update the provided code.

Replace YOUR_APP_API_KEY and YOUR_APP_ID in the code below with your actual keys. This code uses the Test Users segment we created earlier.
3

Run the code.

Run the code in your terminal.
4

Check images and confirmed receipt.

If all setup steps were completed successfully, the test users should receive a notification with an image included:

Push notification with image on iOS and Android

Images will appear small in the collapsed notification view. Expand the notification to see the full image.
5

Check for confirmed receipt.

In your dashboard, go to Delivery > Sent Messages, then click the message to view stats.You should see the confirmed stat, meaning the device received the push.
You have successfully sent a notification via our API to a segment.
  • No image received? Your Notification Service Extension might be missing.
  • No confirmed receipt? Review the troubleshooting guide here.
  • Having issues? Copy-paste the api request and a log from start to finish of app launch into a .txt file. Then share both with support@onesignal.com.

Send an in-app message

In-app messages let you communicate with users while they are using your app.
1

Close or background your app on the device.

This is because users must meet the in-app audience criteria before a new session starts. In OneSignal, a new session starts when the user opens your app after it has been in the background or closed for at least 30 seconds. For more details, see our guide on how in-app messages are displayed.
2

Create an in-app message.

  • In your OneSignal dashboard, navigate to Messages > In-App > New In-App.
  • Find and select the Welcome message.
  • Set your Audience as the Test Users segment we used previously.

Targeting the 'Test Users' segment with an in-app message

3

Customize the message content if desired.

Example customization of in-app Welcome message

4

Set Trigger to 'On app open'.

5

Schedule frequency.

Under Schedule > How often do you want to show this message? select Every time trigger conditions are satisfied.

In-app message scheduling options

6

Make message live.

Click Make Message Live so it is available to your Test Users each time they open the app.
7

Open the app and see the message.

After the in-app message is live, open your app. You should see it display:

Welcome in-app message shown on devices

Not seeing the message?
  • Start a new session
    • You must close or background the app for at least 30 seconds before reopening. This ensures a new session is started.
    • For more, see how in-app messages are displayed.
  • Still in the Test Users segment?
    • If you reinstalled or switched devices, re-add the device to Test Users and confirm it’s part of the Test Users segment.
  • Having issues?
    • Follow Getting a Debug Log while reproducing the steps above. This will generate additional logging that you can share with support@onesignal.com and we will help investigate what’s going on.
You have successfully setup the OneSignal SDK and learned important concepts like:Continue with this guide to identify users in your app and setup additional features.

User identification

Previously, we demonstrated how to create mobile Subscriptions. Now we’ll expand to identifying Users across all their subscriptions (including push, email, and SMS) using the OneSignal SDK. We’ll cover External IDs, tags, multi-channel subscriptions, privacy, and event tracking to help you unify and engage users across platforms.

Assign External ID

Use an External ID to identify users consistently across devices, email addresses, and phone numbers using your backend’s user identifier. This ensures your messaging stays unified across channels and 3rd party systems (especially important for Integrations). Set the External ID with our SDK’s login method each time they are identified by your app.
OneSignal generates unique read-only IDs for subscriptions (Subscription ID) and users (OneSignal ID).As users download your app on different devices, subscribe to your website, and/or provide you email addresses and phone numbers outside of your app, new subscriptions will be created.Setting the External ID via our SDK is highly recommended to identify users across all their subscriptions, regardless of how they are created.

Add Tags

Tags are key-value pairs of string data you can use to store user properties (like username, role, or preferences) and events (like purchase_date, game_level, or user interactions). Tags power advanced Message Personalization and Segmentation allowing for more advanced use cases. Set tags with our SDK addTag and addTags methods as events occur in your app. In this example, the user reached level 6 identifiable by the tag called current_level set to a value of 6.

A user profile in OneSignal with a tag called "current_level" set to "6"

We can create a segment of users that have a level of between 5 and 10, and use that to send targeted and personalized messages:

Segment editor showing a segment targeting users with a current_level value of greater than 4 and less than 10


Screenshot showing a push notification targeting the Level 5-10 segment with a personalized message


The push notification is received on an iOS and Android device with the personalized content

Add email and/or SMS subscriptions

Earlier we saw how our SDK creates mobile subscriptions to send push and in-app messages. You can also reach users through emails and SMS channels by creating the corresponding subscriptions. If the email address and/or phone number already exist in the OneSignal app, the SDK will add it to the existing user, it will not create duplicates. You can view unified users via Audience > Users in the dashboard or with the View user API.

A user profile with push, email, and SMS subscriptions unified by External ID

Best practices for multi-channel communication
  • Obtain explicit consent before adding email or SMS subscriptions.
  • Explain the benefits of each communication channel to users.
  • Provide channel preferences so users can select which channels they prefer.

To control when OneSignal collects user data, use the SDK’s consent gating methods: See our Privacy & security docs for more on:

Prompt for push permissions

Instead of calling requestPermission() immediately on app open, take a more strategic approach. Use an in-app message to explain the value of push notifications before requesting permission. For best practices and implementation details, see our Prompt for push permissions guide.

Listen to push, user, and in-app events

Use SDK listeners to react to user actions and state changes. The SDK provides several event listeners for you to hook into. See our SDK reference guide for more details.

Push notification events

For full customization, see Mobile Service Extensions.

User state changes

In-app message events


Advanced setup & capabilities

Explore more capabilities to enhance your integration:

Mobile SDK setup & reference

Make sure you’ve enabled all key features by reviewing the Mobile push setup guide. For full details on available methods and configuration options, visit the Mobile SDK reference.
Congratulations! You’ve successfully completed the Mobile SDK setup guide.

Need help?Chat with our Support team or email support@onesignal.comPlease include:
  • Details of the issue you’re experiencing and steps to reproduce if available
  • Your OneSignal App ID
  • The External ID or Subscription ID if applicable
  • The URL to the message you tested in the OneSignal Dashboard if applicable
  • Any relevant logs or error messages
We’re happy to help!