Tag Archives: unity

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.

Google Mobile Ads Unity Plugin v3.0.0

Today we're launching version 3.0.0 of the Google Mobile Ads Unity Plugin. The updated Unity package is available for download on our GitHub repo.

Streamlined Build Process

With the v3.0.0 release of the Google Mobile Ads Unity plugin, the process for generating both Android and iOS projects no longer requires additional setup.

Android

The Google Play Services library project no longer has to be included within your Unity project. Instead, the necessary Google Play services client libraries are automatically copied into Unity projects at build time. This functionality is provided via the Unity JarResolver library (linked on our GitHub repo). This change decreases app size and fixes compatibility issues with other Unity plugins that use Google Play services, such as the Google Play Games plugin.

iOS

The Google Mobile Ads Unity plugin now uses CocoaPods to deploy the Google Mobile Ads SDK into the iOS project generated by Unity. The Google Mobile Ads Unity plugin will also configure all necessary build settings for the iOS project.

Custom IAP

This release of the Google Mobile Ads Unity Plugin also brings support for non-default in-app purchases. The non-default purchase flow gives developers full control over the implementation of the billing flow, while allowing for purchase of both consumable and non-consumable products. Steps on how to integrate non-default in-app purchases into your Unity application can be found on our Game Developers guide.

Ad Event Refactoring

This release includes a refactoring of ad events for both banners and interstitials. Take note of the following changes and update projects written against past versions of the Google Mobile Ads Unity plugin.

Old Ad Event New Ad Event
AdLoaded OnAdLoaded
AdFailedtoLoad OnAdFailedToLoad
AdOpened OnAdOpening
AdClosing (deprecated)
AdClosed OnAdClosed
AdLeftApplication OnAdLeavingApplication

The source code and a sample app for the plugin are available on our GitHub repo, as is a changelog for this release. If you have any questions about Unity integration, you can reach us on our forum. Remember that you can also find us on Google+, where we post updates on all of our Google Ads developer products.

Multiple scenes and ads in Unity

When developing with AdMob in Unity, it is a common practice to make your banner ads persist across multiple scenes. This blog post will highlight best practices to accomplish this with the Google Mobile Ads Unity Plugin.

The most straightforward approach is to link the lifecycle of ads to that of the scenes they’re displayed in. When transitioning from one scene to another, existing ads are destroyed before leaving the first scene. New ads can then be created and displayed in the next scene.

The downside of this approach is that every scene transition would result in a new banner request. This may not be desirable if scene transitions are frequent and occur quickly.

An alternative is to use a GameObject as a wrapper for banners or interstitials. By default, each GameObject in a scene will be destroyed once the new scene is loaded (unless you use additive scene loading). However, you can make a GameObject survive across scenes by marking it with DontDestroyOnLoad. You can then use the GameObject.Find method to obtain references to the wrapper GameObject from scripts in other scenes.

Here is an example of how to use a GameObject to wrap banner ads:


// FirstSceneScript.cs
void Start() {
// Create a wrapper GameObject to hold the banner.
GameObject myGameObject = new GameObject("myBannerAdObject");
myGameObject.AddComponent<BannerWrapper>();
// Mark the GameObject not to be destroyed when new scenes load.
DontDestroyOnLoad(myGameObject);
}
The BannerWrapper GameObject is a wrapper for a BannerView.

// BannerWrapper.cs
using System;

using UnityEngine;
using GoogleMobileAds;
using GoogleMobileAds.Api;

public class BannerWrapper : MonoBehaviour {

public BannerView bannerView;

void Start()
{
bannerView = new BannerView(
"your_ad_unit_id", AdSize.SmartBanner, AdPosition.Bottom);
AdRequest request = new AdRequest.Builder().Build();
bannerView.LoadAd (request);

bannerView.Show();
}
}

In SecondSceneScript.cs, which is attached to the second scene, you can find a GameObject by name, get the BannerWrapper component, and access the BannerView:


// SecondSceneScript.cs
void Start () {
GameObject myGameObject = GameObject.Find("myBannerAdObject");
BannerWrapper bannerWrapper = myGameObject.GetComponent();
bannerWrapper.bannerView.Hide();
}

By managing your ads efficiently and seamlessly across scenes, you are sure to provide a better ad experience for your users. If you have any questions about Unity integration, you can reach us on our forum. You can also find our quick-start guide linked here. Remember that you can also find us on Google+, where we have updates on all of our Google Ads developer products.

Google Mobile Ads Unity Plugin v2.3.0

We’re excited to announce the v2.3.0 release of the Google Mobile Ads Unity Plugin! The new release brings support for AdMob in-app purchase ads to the Unity game engine. You can grab the updated Unity package on GitHub.

In-app purchase ads in Unity with AdMob

In-app purchase (IAP) ads are interstitial ads that display offers for your in-app products. They allow users to make purchases directly from within your app as part of your normal ad flow.

Note: The plugin currently only supports IAP ads on Android. iOS support is not yet available.

Before integrating IAP ads into your app, make sure you’ve set up an IAP house ad campaign and created an IAP house ad. You should also install the plugin as explained in the AdMob Unity Quick Start guide.

Once you’ve set up your campaign, there are five steps to integrate IAP ads:

  1. In the AndroidManifest.xml in Assets/Plugins/Android/GoogleMobileAds/Plugin, uncomment the following line to enable billing permissions:
    <!--<uses-permission android:name="com.android.vending.BILLING"/> -->
  2. Create a class that implements the IInAppPurchaseHandler interface. See GoogleMobileAdsDemoScript.cs for an implementation example. You need to define the following methods:
    1. OnInAppPurchaseFinished -- here you credit the user with the purchase, and then call result.FinishPurchase() to finish the transaction.
    2. IsValidPurchase -- check the SKU against valid SKUs and return true if this purchase is valid.
    3. AndroidPublicKey { get; } -- return the public key for your Android app, which you obtain from the Google Play console.
  3. Pass in the above implementation of IInAppPurchaseHandler to InterstitialAd.SetInAppPurchaseHandler.
  4. Make sure you request an in-house IAP ad by setting the correct adUnitId when creating the InterstitialAd. See In-App Purchase Overview for detailed instructions on how to set up IAP house ads in your AdMob account.
  5. Add the Conversion Tracking and Remarketing SDK to the Plugins/Android directory.

That’s it!

An example IAP ad.

If you have any questions, please drop by our forum.

Updates to Unity, C++, and iOS tools for Play game services

Posted by Benjamin Frenkel, Product Manager

To further support all you game developers, we've updated our popular developer tools to give you a consistent set of game services across platforms for a better, more stable experience, with a particular focus on improvements to the Play game services Unity plugin. In addition, we added support for the Nearby Connections API, launched earlier this year at GDC, to our C++ SDK and Unity plugin.

Let’s take a look a closer look!

Unity plugin feature parity and stability improvements

We’ve added full support for Events and Quests in the Unity plugin. If you’re a Unity developer, you can now incorporate Quests into your games and take full advantage of Player Analytics natively within the Unity IDE.

We’ve also listened to feedback from our community of Unity plugin users and made stability improvements to Play game services Multiplayer, Saved Games, and to sign-in. You’ll now have a much better experience integrating with these Play game services, with fewer crashes and glitches.

C++ SDK and Unity support for the Nearby Connections API

We have added support for the Nearby Connections API to our C++ SDK and Unity plugin. You can now easily build awesome second screen and local multiplayer experiences, like this Beach Bugging Racing example, with the development tools you are most comfortable with.

Easier and more stable iOS builds with CocoaPods

We’ve also made major improvements to our Play game services CocoaPods, which simplify dependency management and building App Store packages from Xcode. The CocoaPods will improve building for iOS with the Play game services iOS and C++ SDKs, and the Unity plugin. We also improved the stability of multiplayer on iOS, eliminating many of the issues around accepting match invitations.

Finally, we improved our support for iOS 8, making it easier to set up multiplayer push notifications, and fixing UI compatibility issues.

Quick links to get you started

Play game services developer page: https://developers.google.com/games/services/
Case studies: http://developer.android.com/distribute/stories/games.html

Downloads

Google Mobile Ads Unity Plugin v2.2.1

We have launched the Google Mobile Ads Unity Plugin v2.2.1. The updated v2.2.1 Unity package is available for download on GitHub here.

Multiple ad positions

Google Mobile Ads Unity Plugin v2.2.1 introduces support for additional banner position locations. The full list of banner positions is as follows:

  • Top
  • Bottom
  • TopLeft
  • TopRight
  • BottomLeft
  • BottomRight

The additional positions are specified by setting the AdPosition value when instantiating a bannerView:


//Create a banner at the top-right of the screen.
BannerView bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.TopRight);

iOS Ads SDK 7.0.0 Compatibility

With the v7.0.0 release, the iOS Ads SDK became a module framework and Google Mobile Ads Unity Plugin v2.2.1 complies with this change. For modules to work, you must enable them in the project build settings. Search for "modules", and set Enable Modules to YES. The Link Frameworks Automatically option should be set to YES as well.

Unity 5.0 and ARC

Unity 5.0 has moved out of beta and brings with it support for Automatic Reference Counting (ARC) for iOS. v2.2.1 of the Unity plugin takes advantage of ARC with no additional changes in project settings or code.

The source code and a sample app for the plugin are available on our GitHub repo. A changelog for this release is listed here. If you have any questions about Unity integration, you can reach us on our forum. Remember that you can also find us on Google+, where we have updates on all of our Google Ads developer products.

Google Mobile Ads Unity Plugin 2.1 Adds Interstitial Support

Today, we’re delighted to announce the launch of the Google Mobile Ads Unity Plugin v2.1, now with interstitial ads. You can start playing around with the latest code by grabbing the v2.1 Unity package on GitHub.

Interstitial Ads

There are four steps required to integrate interstitial ads:

  1. Create a new InterstitialAd, specifying your interstitial ad unit ID
  2. Register for the ad events you care about
  3. Load the InterstitialAd with an AdRequest
  4. Show the InterstitialAd at an appropriate place in your app

The first three steps can be performed at the same time, and can even live in its own helper function:


public InterstitialAd CreateAndLoadInterstitial() {
// Initialize an InterstitialAd.
InterstitialAd interstitial = new InterstitialAd("MY_AD_UNIT_ID");
// Register for ad events.
interstitial.AdLoaded += delegate(object sender, EventArgs args) {};
interstitial.AdFailedToLoad += delegate(object sender, AdFailToLoadEventArgs args) {};
interstitial.AdOpened += delegate(object sender, EventArgs args) {};
interstitial.AdClosing += delegate(object sender, EventArgs args) {};
interstitial.AdClosed += delegate(object sender, EventArgs args) {};
interstitial.AdLeftApplication += delegate(object sender, EventArgs args) {};
// Load the InterstitialAd with an AdRequest.
interstitial.LoadAd(new AdRequest.Builder().Build());
}

You should wait to show the interstitial until a good stopping point in your app, for example when the user finishes a level in your game. Remember to check that the interstitial has finished loading before you show it:


// Call this when a level finishes.
public void LevelFinished() {
if (interstitial.isLoaded()) {
interstitial.Show();
}
}

Keep in mind that an interstitial is a one-time use object. Once the interstitial is closed, you can dispose of the object and prepare another one. This can be implemented directly in the AdClosed event.


interstitial.AdClosed += delegate(object sender, EventArgs args)
{
interstitial.Destroy();
interstitial = CreateAndLoadInterstitial();
};

Ad Events now use EventHandlers

In this release, we also changed our ad events to be of type EventHandler instead of Action for both BannerView and InterstitialAd. This means your callback methods now take an object representing the event sender, and an EventArgs:


interstitial.AdLoaded = delegate(object sender, EventArgs args)
{
print(“Interstitial Loaded”);
};

The only event with special event args is AdFailedToLoad. It passes an instance of AdFailedToLoadEventArgs with a Message describing the error.


interstitial.AdFailedToLoad = delegate(object sender, AdFailedToLoadEventArgs args)
{
print("Interstitial Failed to load: " + args.Message);
};

The source code as well as a sample app for the plugin is available on our googleads-mobile-plugins GitHub repo. If you have any questions about Unity integration, you can reach us on our forum. Remember that you can also find us on Google+, where we have updates on all of our Google Ads developer products.

Labels: mobile_ads_sdk, unity

Monetizing Unity Mobile Apps Just Got Easier

Calling all Unity app developers! We are excited to announce the launch of version 2.0 of the Google Mobile Ads Unity Plugin. The new version comes with a completely rewritten, but much more flexible, API. It includes the following new features:

  • A single package supporting both Android and iOS
  • Support for running apps in the Unity editor
  • Ability to create multiple banner instances
  • Ability to create banners of any size
  • Flexible ad request targeting
  • and much more!

Taking a closer look at how to integrate the plugin, a typical banner request in v2.0 looks like this:


BannerView bannerView = new BannerView(
"YOUR_AD_UNIT_ID", AdSize.Banner, AdPosition.Top);
AdRequest request = new AdRequest.Builder().Build();
bannerView.LoadAd(request);

For custom banner sizes, simply pass in an AdSize object into the BannerView constructor:


AdSize adSize = new AdSize(250, 250);
BannerView bannerView = new BannerView(
"YOUR_AD_UNIT_ID", adSize, AdPosition.Top);

Want to pass additional targeting parameters? No problem! Set your custom targeting when building the AdRequest:


AdRequest request = new AdRequest.Builder()
.AddTestDevice(AdRequest.TestDeviceSimulator)
.AddTestDevice("0123456789ABCDEF0123456789ABCDEF")
.AddKeyword("unity")
.SetGender(Gender.Male)
.SetBirthday(new DateTime(1985, 1, 1))
.TagForChildDirectedTreatment(true)
.Build();

Listening for ad events is also extremely straightforward. Register for the callbacks you care about:


bannerView.AdLoaded += HandleAdLoaded;
bannerView.AdFailedToLoad += HandleAdFailedToLoad;
bannerView.AdOpened += HandleAdOpened;
bannerView.AdClosing += HandleAdClosing;
bannerView.AdClosed += HandleAdClosed;
bannerView.AdLeftApplication += HandleAdLeftApplication;



public void HandleAdLoaded()
{
print("HandleAdLoaded event received.");
}

You can also manage the lifecycle of each BannerView by calling show(), hide(), or destroy().

To get access to these awesome features, check out the source code. Also stay tuned for upcoming support for interstitial ads.

If you have any feature requests or bug reports against the plugin, track it! If you have questions about how to use the plugin, speak up! And if you just want the latest news on what’s going on in the wonderful world of Google Ads, circle us!