Initialize the MoPub SDK for Unity

The MoPub 5.0 SDK introduces a new API for initialization called MoPub.InitializeSdk(). This API is required for a number of new functionalities, including:

v5.0.0 to v5.4.1:

  • GDPR consent mechanisms
  • Rewarded video pre-initialization

v5.5.0 and above:

  • GDPR consent mechanisms
  • Mediation SDKs initialization
  • Logging
  • Advanced Bidding
  • Legitimate Interest

There are two ways of handling the initialization: Using the MoPubManager starting in 5.8.0+ (recommended), or manually. Using the manual approach, you will have to write initialization code to set up MoPub’s essential initialization properties. When using the MoPubManager, those properties are abstracted into a persisting Unity Prefab, which you can add to your scene and handle the logic using Unity Editor UI.

Directly within the Unity editor, the MoPub Manager lets you specify custom data (e.g. MoPub’s and mediation IDs), callbacks, and options to be consumed downstream by mediation adapters and SDKs. As of the 5.8.0 release of the MoPub Unity SDK, you can use the MoPub Manager to streamline how you configure initialization options for both MoPub and any other mediated network SDK.

All of the settings that you need to set via code before are now abstracted behind the MoPub Manager UI. You can utilize the checkboxes, text fields, and dropdown menus to make your selections. The MoPub Unity SDK will handle transferring your selections to the underlying platform SDK and adapters. The prefab is configured such that it would persist across your multiple scenes.

To get started, drag and drop the MoPubManager prefab from Assets/MoPub/Prefabs onto your scene. Once done, you should see a UI that looks similar to this:

MoPub Manager

You can begin customizing any settings to fit your use case. For details, hover on the setting to read more about what it does and what you can pass to it. Some of the settings the MoPub Manager supports include:

Setting Description
Auto Initialize On Start Check this option to automatically initialize the MoPub SDK in Start(). The SDK must be initialized before you can request ads. If unchecked, you must manually initialize the SDK.
Android/iOS Ad Unit ID Any valid ad unit ID from your app to be used when initializing the MoPub SDK.
Allow Legitimate Interest Check this option to opt into allowing supported mediation networks to collect user information on the basis of legitimate interest. For more details read here Note: you must be a whitelisted publisher in order to use this functionality (it is a no-op otherwise).
Log Level Specify a log verbosity (none/info/debug) for the MoPub and supported network SDKs.
Callbacks Subscribe to a list of callbacks to listen to for events such as initialization completion, consent dialog lifecycle. If you have code that runs as a result of a callback, find the right callback and specify the object where your desired function can be found that needs to run when the callback fires.
MoPubConsent The MoPubConsent script on the Prefab manages the GDPR consent status and dialog. If the Auto Show Consent Dialog checkbox is enabled, the script will automatically load and show the GDPR consent dialog, so you don’t need code to set up that logic anymore. (This only works with the stock MoPub consent dialog.)
Network Configuration (Mediation) You can pass custom data to specific ad networks during initialization. Select a network in the “Add Network Configuration” dropdown menu to add a configuration script for that network to the gameobject.

The script will have fields for network configuration and global mediation settings that are relevant to that network. Note: This operation only passes data for network SDK initialization. Note: If you need to pass data for fields whose values can only be determined at runtime, there is a way to do that. Check the Passing Data at Runtime section below for details.

During initialization, the values passed into the MoPubManager will take higher precedence compared to those inputted on the MoPub dashboard. Ensure you have an appropriate use case before enabling the MoPubManager. For testing purpose you have an alternative option - please refer to the Testing Mode section.

Advanced

Passing Data at Runtime

The callback OnSdkConfiguration is called once configuration is prepared, and it’s about to be used for initialization. At this point, you can listen to the OnSdkConfiguration callback in order to add additional data (not present on MoPub Manager Prefab) to certified ad network configuration dictionaries. Below, you can find steps to include additional data to a network configuration.

To pass data to the SDK initialization for fields that can only be determined at that time, add a script to the MoPubManager implementing OnSdkConfiguration(MoPub.SdkConfiguration config). This will be called via SendMessage when the MoPubManager builds its SdkConfiguration value during initialization. To access the MediatedNetwork object for a specific network, use the index operator with the network name (e.g., config["NetworkName"]). That gives you access to the NetworkConfiguration and MediationSettings dictionaries, which you can alter by adding or changing key/value entries in place. Here is an example:

   void OnSdkConfiguration(MoPub.SdkConfiguration config)
   {
       var userId = // compute a unique string for this user

       var options = config["NetworkName"];
       if (options != null)
           options.NetworkConfiguration["userId"] = userId;
     // or options.MediationSettings["userId"] = userId;
   }

Testing Mode

If you would like to pass in a separate set of SDK and network configuration values for QA/testing builds, use the MoPubManagerTesting gameobject. This is included in the MoPubManager prefab as a child object of the root object (which holds the “production” build MoPubManager script). The child object is normally disabled. If you activate it and then build the app at runtime the configurations on it override those of the parent since it takes over the SDK initialization process. Do this for test builds, so that you can keep your test configuration separate from your production configuration. The inspector panel for the testing object has a button to copy configuration values from the parent production object, to save time entering most of the values that might not change. Note: The consent management script and all UnityEvent callbacks on the parent object are still active in a test build.

MoPub Manager

Option 2. Initialize MoPub manually

You only need to initialize once using any valid ad unit ID from your app. Ad requests should only be made once the SDK initialization has completed. You can simply register for the OnSdkInitializedEvent callback event and create your own handler as shown in the example below.

  1. In your app’s Start(), instantiate a MoPub.SdkConfiguration object with any valid ad unit ID from your app, your mediation settings (optional), (optional) log level, (optional) map of configurations for networks, and (optional) a list of adapter configuration class names to initialize.
  2. Call MoPub.InitializeSdk() and pass in the MoPub.SdkConfiguration object.
    • You have the option of using the MoPubManager prefab while initializing the MoPub SDK programmatically. To do so, leave the Auto Initialize On Start checkbox unchecked. Then, instead of passing in a new MoPub.SdkConfiguration object, you can call MoPub.InitializeSdk(MoPubManager.Instance.SdkConfiguration);. This will use the values you enter into the MoPubManager prefab but allow you to make the initialization call at your convenience.

Network SDK initialization

SDK initialization will automatically attempt to initialize all known networks. However, publishers will be given the option to specify additional networks via the SDK configuration object as shown in the example below. Note: you can use NetworkConfiguration to pass network configurations required for pre-initialization. Otherwise, your first attempt to pre-initialize mediated networks will be a no-op because no network data is cached at this point. All subsequent attempts to pre-initialize should succeed for the duration of the app’s lifecycle.

Behavior Matrix

Below is a breakdown of the different use cases of network initialization and the corresponding behaviors.

  Initial App Launch All App Launches
Traditional Mediation: No Data At this time, there are no network parameters entered on the UI cached by the MoPub SDK, so network initialization will happen without publisher-specific data. Depending on the mediation network SDK, initializing with no data may mean that no action will occur on its end. Once the initial ad request has succeeded, data will be cached and made available for use in network initialization attempts on subsequent app launches when MoPub initializes. See Traditional Mediation: With Data - Initial App Launch for a power use case. Select networks do not initialize due to different code requirements (e.g. different types of Context). When this is the case, the network SDK in question will skip initializing on app launches when MoPub initializes, and will be initialized at the time of the ad request. On Android, networks known to not initialize due to Context restrictions are Chartboost, Unity Ads, and ironSource.
Traditional Mediation: With Data Publishers can pass in specific parameters for network initialization via withMediatedNetworkConfiguration(). This way, there are always data with which to initialize networks, even on the very first app launches. Note that if this approach is used, the publisher-supplied data will remain active and be used for subsequent ad requests, and parameters entered on the MoPub UI will be ignored. Select networks do not initialize due to different code requirements (e.g. different types of Context). When this is the case, the network SDK in question will skip initializing on app launches when MoPub initializes, and will be initialized at the time of the ad request. On Android, networks known to not initialize due to Context restrictions are Chartboost, Unity Ads, and ironSource.
Advanced Bidding: No Data See Traditional Mediation: No Data - Initial App Launch. Typically, there is no bidding token in this case because the network SDK does not initialize, resulting in the initial ad request not being treated as an Advanced Bidding request. Refer to these instructions for a workaround. See Traditional Mediation: All App Launches for context. Refer to these instructions to initialize network SDKs before MoPub.
Advanced Bidding: With Data See Traditional Mediation: With Data - Initial App Launch. There likely is a bidding token in this case (but that is not guaranteed), because the network SDK could initialize. In case the network SDK does not finish initializing, there may be no bidding token. Refer to these instructions for a workaround to initialize network SDKs before MoPub. See Traditional Mediation: All App Launches for context. Refer to these instructions to initialize network SDKs before MoPub.

Logging Information

The MoPub 5.5.0 SDK enhances the logging experience to include more detailed information such as adapter version, SDK version and ad life cycle events and operations. You can set Debug, Info or None using MoPubBase.LogLevel during initialization.

Legitimate Interest

The MoPub SDK 5.5.0 now enables mediated networks to collect your user’s personal data based on legitimate interest basis when publishers opt-in. For more details read here. You can enable the legitimate interest flag using the API AllowLegitimateInterest during initialization.

Initialize Custom Ad Networks

Follow these instructions to initialize custom network SDKs not listed on Supported Mediation Partners:

  • Follow this guide to write adapter configuration class for your network for Android.
  • Follow this guide to write adapter configuration class for your network for iOS.
  • Set the network configuration options for a given mediated network class name using MoPub.MediatedNetwork. Refer to the example below.

Example

private void Start()
    {
        // NOTE: the MoPub SDK needs to be initialized on Start() to ensure all other objects have been enabled first.
        var anyAdUnitId = _bannerAdUnits[0];
        MoPub.InitializeSdk(new MoPub.SdkConfiguration {
            AdUnitId = anyAdUnitId,

            // Set desired log level here to override default level of MPBLogLevelNone
            LogLevel = MoPubBase.LogLevel.MPBLogLevelDebug,

            // Uncomment the following line to allow supported SDK networks to collect user information on the basis
            // of legitimate interest.
            //AllowLegitimateInterest = true,

            // Specify the mediated networks you are using here:
            MediatedNetworks = new MoPub.MediatedNetwork[]
            {
                // Example using AdMob.  Follow this template for other supported networks as well.
                // Note that keys must be strings, and values must be JSON-serializable (strings only, for MoPubRequestOptions).
                new MoPub.SupportedNetwork.AdMob
                {
                    // Network adapter configuration settings (initialization).
                    NetworkConfiguration = new Dictionary<string,object> {
                        { "key1", value },
                        { "key2", value },
                    },

                    // Global mediation settings (per ad request).
                    MediationSettings = new Dictionary<string,object> {
                        { "key1", value },
                        { "key2", value },
                    },

                    // Additional options to pass to the MoPub servers (per ad request).
                    MoPubRequestOptions = new Dictionary<string,object> {
                        { "key1", "value" },
                        { "key2", "value" },
                    }
                },

                // Example using a custom network adapter:
                new MoPub.MediatedNetwork
                {
                    // Specify the class name that implements the AdapterConfiguration interface.
                #if UNITY_ANDROID
                    AdapterConfigurationClassName = "com.mopub.mobileads.YourNetworkAdapterConfiguration",  // include the full package name.
                #else // UNITY_IOS
                    AdapterConfigurationClassName = "MyNetworkAdapterConfiguration",
                #endif

                    // Specify the class name that implements the MediationSettings interface.
                    // Note: Custom network mediation settings are currently not supported on Android.
                #if UNITY_IOS
                    MediationSettingsClassName = "classname",
                #endif

                    // Fill in settings and configuration options the same way as for supported networks:

                    NetworkConfiguration = new Dictionary<string,object> {
                        { "key1", value },
                        { "key2", value },
                    },

                #if UNITY_IOS  // See note above.
                    MediationSettings    = new Dictionary<string,object> {
                        { "key1", value },
                        { "key2", value },
                    },
                #endif

                    MoPubRequestOptions  = new Dictionary<string,object> {
                        { "key1", value },
                        { "key2", value },
                    },
                }
            },
        });

        // register for initialized callback event in the app
        MoPubManager.OnSdkInitializedEvent += OnSdkInitializedEvent;

        // create your handler
        private void OnSdkInitializedEvent(string adUnitId)
    	{
        	// The SDK is initialized here. Ready to make ad requests.
    	}
    }

Last updated October 16, 2019

TWITTER, MOPUB, and the Bird logo are trademarks of Twitter, Inc. or its affiliates. All third party logos and trademarks included are the property of their respective owners.

© 2019 MoPub (a division of Twitter, Inc.)