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:

For older MoPub SDK versions (v5.0.0 to v5.4.1), initializing is required for:

  • GDPR consent mechanisms
  • Rewarded video pre-initialization

For MoPub SDK v5.5.0 and higher, initializing is required for:

  • GDPR consent mechanisms
  • Initialization of mediation SDKs
  • Logging
  • Advanced Bidding
  • Legitimate Interest

There are two ways of handling the initialization: Using the MoPubManager starting with MoPub SDK v5.8.0+ (recommended), or manually. If you use the manual approach, you must write initialization code to set up MoPub’s essential initialization properties. By contrast, if you use the MoPubManager, those properties are abstracted into a persisting Unity Prefab, which you can add to your scene and handle the logic using the Unity Editor UI.

Directly within the Unity editor, the MoPub Manager lets you specify custom data (such as MoPub’s and mediation IDs), callbacks, and options that are consumed downstream by mediation adapters and SDKs. Starting with MoPub SDK v5.8.0, you can use the MoPub Manager to streamline how you configure initialization options for both MoPub and any other mediated network SDK.

All the settings that you previously had to set via code are now abstracted behind the MoPub Manager UI. You can use the checkboxes, text fields, and drop-down menus to make your selections. The MoPub Unity SDK handles transferring your selections to the underlying platform SDK and adapters. The prefab is configured to persist across your multiple scenes.

To get started, drag and drop the MoPubManager prefab from Assets/MoPub/Prefabs onto your scene. You should then 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 a 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. Leaving it unchecked means 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 refer to the Legitimate Interest section of our GDPR Guide. Note: you must be a whitelisted publisher to use this functionality; otherwise, it fails.
Log Level Specify log verbosity (‘none’, ‘info’ or ‘debug’) for the MoPub SDK and for supported network SDKs.
Callbacks Subscribe to a list of callbacks to listen to for events such as initialization completion and 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 drop-down menu to add a configuration script for that network to the gameobject.

The script has fields for network configuration and global mediation settings that are relevant to that network.

Notes:
- This operation only passes data for network SDK initialization.
- To pass data for fields whose values can only be determined at runtime, refer to the Passing Data at Runtime section below for details.

During initialization, the values passed into the MoPubManager take priority over values that were input on the MoPub dashboard. Ensure that you have an appropriate use case before enabling the MoPubManager. There is an alternative option for testing purposes; refer to the Testing Mode section below.

Advanced Use Cases of the MoPub Manager Initialization

Passing Data at Runtime

The callback OnSdkConfiguration is called when configuration is prepared and 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 is 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 (for example, 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

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, because it takes over the SDK initialization process. Do this for test builds, to 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 the time of entering most of the values that may 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

Initialize once per app’s lifecycle, typically on app launch, using any valid ad unit ID from your app. Make no ad requests until 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() method, instantiate a MoPub.SdkConfiguration object with

    • any valid ad unit ID from your app
    • your mediation settings (optional)
    • log level (optional)
    • map of configurations for networks (optional)
    • a list of adapter configuration class names to initialize (optional)
  2. Call MoPub.InitializeSdk() and pass in the MoPub.SdkConfiguration object.

You can use 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 automatically attempts to initialize all known networks. However, publishers can specify additional networks via the SDK configuration object as shown in the example below.

You can use NetworkConfiguration to pass network configurations required for pre-initialization. Otherwise, expect your first attempt to pre-initialize mediated networks to fail, because no network data is cached at this point. All your subsequent attempts to pre-initialize should succeed for the duration of the app’s life.

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, the MoPub SDK does not cache any network parameters entered in the UI, so network initialization occurs without publisher-specific data. Depending on the mediation network SDK, initializing with no data may result in no action on the part of that network SDK. After the initial ad request succeeds, data is cached and available for use in network initialization attempts when MoPub initializes on subsequent app launches. Refer to Traditional Mediation: With Data - Initial App Launch for a power use case. Some networks do not initialize because of different code requirements (for example, different types of Context). When this happens, that network skips initializing when MoPub initializes on app launches, but 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, data is always available to initialize networks, even on the very first app launches. Note that with this approach, the publisher-supplied data remains active and is used for subsequent ad requests, and parameters entered on the MoPub UI are ignored. Some networks do not initialize because of different code requirements (for example, different types of Context). When this happens, that network skips initializing when MoPub initializes on app launches, but will be initialized at the time of the ad request. On Android, networks known to not initialize due to Context restrictions are 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 our instructions to initialize your network SDKs for Advanced Bidding for a workaround. See Traditional Mediation: All App Launches for context. Refer to our instructions to initialize your network SDKs for Advanced Bidding 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 this 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 our instructions to initialize your network SDKs for Advanced Bidding for a workaround to initialize network SDKs before MoPub. See Traditional Mediation: All App Launches for context. Refer to our instructions to initialize your network SDKs for Advanced Bidding to initialize network SDKs before MoPub.

Logging Information

The MoPub SDK v5.5.0 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 v5.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, refer to the Legitimate Interest section of our GDPR Guide. 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 among the Supported Mediation Partners:

  • Follow the instructions about custom ad networks in our initialization article for Android or iOS to write an adapter configuration class for your network.

  • 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 March 23, 2020

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.

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