Create custom events

Custom events enable publishers using AdMob Mediation to add waterfall mediation for a third-party ad network that isn't one of AdMob's supported ad networks. This guide explains how to use an existing custom event built for Android and iOS in a Unity project.

Prerequisites

  • Complete Get Started. Your Unity app should already have the Google Mobile Ads Unity plugin imported.

  • Custom event adapters already built for Android and iOS. To create custom event adapters, refer to our custom events guides on Android and iOS.

Define a custom event

In order for a custom event to participate in mediation, the custom event must be defined in the AdMob UI. Add a custom event to both of your Android and iOS mediation groups.

This screenshot shows some sample custom event settings:

How to fill out parameters
Class Name (iOS)

For iOS, enter the name of the class that implements the custom event.

If your class is implemented in Swift, you need to prefix the class name with the name of its app / framework module (for example, appName.className).

Target name is required if you have multiple targets in your project or if the project name is different from the target name. With the target name, it would look like this: appName_targetName.className. In addition, remember to replace any non-alphanumeric characters such as dashes with underscores.

Class Name (Android) For Android, make sure the value you give for the Class Name is the fully qualified class name for Android (for example com.google.ads.mediation.sample.customevent.SampleCustomEvent).
Label Enter a unique name for the event.
Parameter If you wish to pass a string argument to your custom event, for example an ad unit ID.

Import custom event libraries

Custom events may require additional libraries to be included to work correctly. For example this may include libraries for:

  • The Android third-party SDK
  • The Android third-party custom event
  • The iOS third-party ad SDK
  • The iOS third-party custom event

Types of libraries

There are multiple ways to import Android/iOS code into a Unity project, including:

  • Importing pre-built Android/iOS artifacts using the External Dependency Manager for Unity
  • Importing AAR plug-ins and Android libraries
  • Importing Java and Kotlin source files
  • Importing iOS source files and static libraries

Depending on how the libraries you use are packaged, you may need a different import strategy for each library. Each option is discussed in more detail below.

Import pre-built artifacts from Maven or CocoaPods using the External Dependency Manager for Unity. This plugin is included with the GoogleMobileAds plugin.

To import existing artifacts, create a configuration file to define your imports. This file name and path have special requirements:

  • The file must exist in the /Editor/ folder.
  • The filename must end with Dependencies.xml.

For example, to import custom event's adapters for a hypothetical ad network named AdPub, create the file:

Assets/AdPub/Editor/AdPubDependencies.xml

Next, define your dependencies inside the AdPubDependencies.xml file. Rules for configuring the imports can be found at External Dependency Manager for Unity Getting Started guide. The code snippet below includes the Android/iOS SDK and custom event libraries for a hypothetical "AdPub" ad network.

Assets/AdPub/Editor/AdPubDependencies.xml

<dependencies>
  <androidPackages>
    <androidPackage spec="com.adpub.android:adpub-sdk:1.0.0" />
    <androidPackage spec="com.adpub.android:adpub-custom-event:1.0.0">
      <repositories>
        <repository>https://repo.maven.apache.org/maven2/</repository>
        <repository>https://dl.google.com/dl/android/maven2/</repository>
      </repositories>
    </androidPackage>
  </androidPackages>
  <iosPods>
    <iosPod name="AdPubSDK" version="1.0" />
    <iosPod name="AdPubCustomEvent" version="1.0">
      <sources>
        <source>https://github.com/CocoaPods/Specs</source>
      </sources>
    </iosPod>
  </iosPods>
</dependencies>

The External Dependency Manager will automatically monitor for configuration changes and resolve dependencies. You may also execute manual resolution with the following menu command:

Assets > External Dependency Manager > Android Resolver > Force Resolve

Import AAR plug-ins and Android libraries

Unity supports importing *.aar files as well as Android library projects. If your Android custom event is packaged this way, see AAR plug-ins and Android Libraries for instructions on how to include those files in your Unity project.

Import Java and Kotlin source files

Starting in Unity 2018.2 or higher, if your Android custom event code comprises of uncompiled *.java or *.kt files, you can use Java or Kotlin source files as plug-ins.

Import iOS source files and static libraries

Unity supports *.framework artifacts, *.h, and *.m source files. Importing iOS artifacts and source files is explained in Unity's guide for native plug-ins.

Test custom events with Ad Inspector

Ad inspector can be used to test that custom events have been imported correctly into your application. Ad inspector can be open with just gestures or programmatically with minimal code.

(Optional) Call third-party SDK native methods from C# scripts

Third-party ad network SDKs may have special requirements which require calling Android/iOS methods directly. The process for calling into Android/iOS methods directly are as follows:

  1. Defining a common interface for platform clients.
  2. Implementing a default client for unsupported platforms.
  3. Implementing an Android client for calling Android methods.
  4. Implementing an iOS client for calling iOS methods.
  5. Implementing a client factory to conditionally switch between iOS and Android clients.
  6. Defining an API for accessing all third-party ad network SDK functionalities.

The section below walks through how these steps are implemented for a hypothetical ad network called "AdPub", showing how to define a C# API that can call into the following methods on Android/iOS.

Android

package com.adpub.android;

public class AdPubSdk
{
    public static void setHasUserConsent(boolean hasUserConsent);
}

iOS

@interface AdPubSdk : NSObject
+ (void)setHasUserConsent:(BOOL)hasUserConsent;
@end

Define a common interface for platform clients

Create an IAdPubClient interface with a method that represents the underlying Android and iOS API.

Assets/AdPub/Common/IAdPubClient.cs

namespace AdPub.Common
{
    public interface IAdPubClient
    {
        ///<summary>
        /// Sets a flag indicating if the app has user consent for advertisement.
        ///</summary>
        void SetHasUserConsent(bool hasUserConsent);
    }
}

Define a default client for unsupported platforms

Create a DefaultClient class implementing the IAdPubClient interface that just logs the method name. We will use this implementation for the Unity editor UI and all platforms other than Android and iOS.

Assets/AdPub/Common/DefaultClient.cs

namespace AdPub.Common
{
    public class DefaultClient : IAdPubClient
    {
        public void SetHasUserConsent(bool hasUserConsent)
        {
            Debug.Log("SetHasUserConsent was called.");
        }
    }
}

Implement an iOS platform client

Create an iOSAdPubClient class implementing the IAdPubClient interface on iOS. This implementation uses InteropServices to call the setHasUserConsent() method in the iOS AdPubSdk class.

Assets/AdPub/Platforms/iOS/iOSAdPubClient.cs

// Wrap this class in a conditional operator to make sure it only runs on iOS.
#if UNITY_IOS

// Reference InteropServices to include the DLLImportAttribute type.
using System.Runtime.InteropServices;

using AdPub.Common;

namespace AdPub.Platforms.Android
{
    public class iOSAdPubClient : IAdPubClient
    {
        public void SetHasUserConsent(bool hasUserConsent)
        {
            GADUAdPubSetHasUserConsent(hasUserConsent);
        }

        [DllImport("__Internal")]
        internal static extern void GADUAdPubSetHasUserConsent(bool hasUserConsent);
    }
}
#endif

Next, implement the GADUAdPubSetHasUserConsent() method that was defined above. Create AdPubClientBridge.m with a C method GADUAdPubSetHasUserConsent() to handle the method call from Unity, and invoke the AdPubSDK.

AdPubClientBridge is an iOS source file and must be placed inside the Plugins/iOS folder as explained in Unity's guide for native plug-ins.

Assets/AdPub/Plugins/iOS/AdPubClientBridge.m

#import <AdPubSDK/AdPubSDK.h>

void GADUAdPubSetHasUserConsent(BOOL hasUserConsent) {
  [AdPubSDK setHasUserConsent:hasUserConsent];
}

Implement an Android platform client

Create an AndroidAdPubCient class implementing the IAdPubClient interface on Android. This implementation uses the Android Java helper classes to call the Android static method setHasUserConsent().

As the Android Java helper classes are only available during the Android runtime, you can prevent compilation errors using the UNITY_ANDROID compiler directive to wrap the class as shown below. Alternatively, you can use Assembly definitions on Unity 2017.4 and later to solve this issue.

Assets/AdPub/Platforms/Android/AndroidAdPubClient.cs

// Wrap this class in a conditional operator to make sure it only runs on Android.
#if UNITY_ANDROID

// Reference the UnityEngine namespace which contains the JNI Helper classes.
using UnityEngine;

using AdPub.Common;

namespace AdPub.Platforms.Android
{
    public class AndroidAdPubClient : IAdPubClient
    {
        public void SetHasUserConsent(bool hasUserConsent)
        {
             // Make a reference to the com.adpub.AdPubSDK.
            AndroidJavaClass adPubSdk = new AndroidJavaClass("com.adpub.AdPubSdk");

            // Call the native setHasUserConsent method of com.adpub.AdPubSDK.
            adPubSdk.CallStatic("setHasUserConsent", hasUserConsent);
        }
    }
}
#endif

Create a factory method to return the correct client implementation

Now that you have implementations of the client for every platform, create an AdPubClientFactory class to return the correct implementation of the IAdPubClient interface depending on the runtime platform. This class uses compiler directives to return the correct IAdPubClientclient.

Assets/AdPub/Common/AdPubClientFactory.cs

namespace AdPub.Common
{
    public class AdPubClientFactory
    {
        // Return the correct platform client.
        public static IAdPubClient GetClient()
        {
#if   !UNITY_EDITOR && UNITY_ANDROID
            return new AdPub.Platforms.Android.AndroidAdPubClient();
#elif !UNITY_EDITOR && UNITY_IOS
            return new AdPub.Platforms.iOS.iOSAdPubClient();
#else
            // Returned for the Unity Editor and unsupported platforms.
            return new DefaultClient();
#endif
        }
    }
}

Define a public API for each interface method

Create an AdPubApi class that has method calls for each client method in your IAdPubClient interface. This class uses the AdPubClientFactory to get an instance of the IAdPubClient and calls that client for the underlying SDK functionalities.

Assets/AdPub/AdPubApi.cs

using AdPub.Common;

namespace AdPub
{
    public class AdPubApi
    {
        private static readonly IAdPubClient client = GetAdPubClient();

        // Returns the correct client for the current runtime platform.
        private static IAdPubClient GetAdPubClient()
        {
            return AdPubClientFactory.GetClient();
        }

        // Sets the user consent using the underlying SDK functionality.
        public static void SetHasUserConsent(bool hasUserConsent)
        {
            client.SetHasUserConsent(hasUserConsent);
        }
    }
}

Call your newly defined API

Here is how you can call the API defined above:

Assets/Scripts/AdPubController.cs

using UnityEngine;
using AdPub;

public class AdPubController : MonoBehaviour
{
    // TODO: Get consent from the user and update this userConsent field.
    public bool userConsent;

    // Called on startup of the GameObject it's assigned to.
    public void Start()
    {
        // Pass the user consent to AdPub.
        AdPubApi.SetHasUserConsent(userConsent);
    }
}

Additional third-party ad network adapter examples

Visit the Google Mobile Ads Unity Plugin Github repository for additional examples of third-party mediation adapters implementing C# APIs to wrap calls to iOS and Android methods.