Handling Android ad events in Unity

Registering for banner and interstitial ad events is a handy way for Unity developers using the Google Mobile Ads Unity Plugin to track ad lifecycle events -- things like when an ad is loaded or when an ad click causes the app to be backgrounded. For Unity developers deploying to the Android platform, though, it's important to be aware that ad event handler methods are not invoked on the main thread. As a consequence, Unity methods that must be called on the main thread cannot be executed within ad event handler methods.

Consider the following example:


AudioSource audio = GetComponent<AudioSource>();
...
public void HandleInterstitialClosed(object sender, EventArgs args)
{
audio.mute = false;
}

The code above, which modifies the volume of an audio source from within an ad event handler method, results in the following error:

ArgumentException: set_volume can only be called from the main thread

To get around this, we recommend setting a flag when an event happens, and polling for a state change within the Update() method of your Unity script.

For actions required to be performed on the main thread after showing an ad, set a flag on the OnAdClosed ad event. The update method can poll the value of this flag and perform actions as necessary. The code below illustrates how to implement this approach.


private bool interstitialClosed;

void Start()
{
InterstitialAd interstitial = new InterstitialAd("YOUR_AD_UNIT_ID");
interstitial.OnAdClosed += HandleInterstitialClosed;
interstitialClosed = false;
...
}

void Update()
{
if (interstitialClosed)
{
// Perform actions here.
audio.mute = false;
}
}

public void HandleInterstitialClosed(object sender, EventArgs args)
{
interstitialClosed = true;
}

If you have any questions about Unity integration, you can reach us on our forum. You can also find our quick-start guide here. Remember that you can also find us on Google+, where we have updates on all of our Google Ads developer products.