Monday, December 19, 2016

Advertising in your Unity game

5:37 AM Posted by Kerim , , , No comments
We, developers, want to earn some money from what we've developed, an app or a game. So one of the ways of earning some money from your games is to publish advertisement. There are lots of advertisement networks out there but I think the first one that came to someone's mind is AdMob. It's Google's and it supports Unity very well.

So let's see how we integrate the AdMob ads to our next hit game!

Just note that AdMob doesn't support Windows platforms anymore. So, for Windows platforms, I'm planning to write another article. Please stay tune!


Create an account on AdMob


The obvious one. Just go to the https://www.google.com/admob/ and signup or just sign in with your Google account if you have one.

Create a new Ad

Now, after signing in to your AdMob account, on https://apps.admob.com/ click the Monetize tab and click Monetize New App button.






You don't need to have an existing game to add a new app. But if you currently have it in one of the stores just search for it and add it. Otherwise, you'll need to add it manually by entering the App Name and Platform which can be Android or iOS.





Now, we need to select the ad type to display in our game. I love the interstitial ads so I'll stick with it. But you can try other ad types too. For example the Banner type is what we see in lots of apps and games and it typically stays on screen  and rotates different ads without disappearing.

You can always add more than one ad units for your game. So, if you want to display banner and also interstitial ads, that's possible. Just repeat the steps for another type of ad.






And that's it. We can skip the Firebase Analytics section.





Now, just note the App Id and Ad unit Id somewhere because we'll need those values when we'll write the ad code in our Unity game.

Jump to the game!

Ok. We're done with the AdMob ad setup. Now, we can implement our ad logic in Unity.

Well.. How can we communicate with AdMob ad servers within our game? The answer is… by using Google Mobile Ads Unity Plugin!

Google Mobile Ads Plugin

Navigate to https://github.com/googleads/googleads-mobile-unity/releases and download the GoogleMobileAds.unitypackage file.

Now, open the downloaded file by double clicking it and Unity will display the package importing window.





Just leave all the files as checked and click Import.

AdManager

Now, we need our custom logic to implement the ad displaying thing. Let's add a new C# script and name it AdManager.

AdManager class is reponsible for initializing the AdMob, requesting new ads and displaying those ads when needed.


using UnityEngine;
using System.Collections;
using System;
#if (UNITY_ANDROID || UNITY_IPHONE)
using GoogleMobileAds.Api;
#endif

public class AdManager : MonoBehaviour {

#if UNITY_EDITOR
        string adUnitId = "unused";
#elif UNITY_ANDROID
        string adUnitId = "ca-app-pub-xxx";
#elif UNITY_IPHONE
        string adUnitId = "ca-app-pub-yyy";
#else
        string adUnitId = "unexpected_platform";
#endif

#if (UNITY_ANDROID || UNITY_IPHONE)
 InterstitialAd interstitial;

    /// <summary>
    /// Show ads after playing the game this many times
    /// </summary>
    public int AdCycle = 3;

    int currentShowRequest = 0;

    public bool AdIsActive;


    void Awake()
    {
        DontDestroyOnLoad(this.gameObject);
    }

    // Use this for initialization
    void Start () {

        if (AdIsActive)
            RequestAd();
 }
 

    public void RequestAd()
    {
        if (interstitial != null)
            interstitial = null;

        interstitial = new InterstitialAd(adUnitId);
        
        

        AdRequest request = new AdRequest.Builder()
    .AddTestDevice(AdRequest.TestDeviceSimulator)       // Simulator.
    .AddTestDevice("53BE334F327AD478DEE92AF1B98F7AAA")  // test device.
    .Build();

        interstitial.OnAdFailedToLoad += İnterstitial_OnAdFailedToLoad;
        interstitial.OnAdOpening += İnterstitial_OnAdOpening;

        // Load the interstitial ad
        interstitial.LoadAd(request);
    }

    private void İnterstitial_OnAdOpening(object sender, System.EventArgs e)
    {
        // ad is opening..
    }

    private void İnterstitial_OnAdFailedToLoad(object sender, AdFailedToLoadEventArgs e)
    {
        // ad failed to load. we can request another one
    }

    public void ShowAd()
    {
        
        if (!AdIsActive)
            return;
if (++currentShowRequest < AdCycle)
            return;


        if (interstitial.IsLoaded())
        {
            interstitial.Show();
            currentShowRequest = 0;
            RequestAd();
        }
    }



#endif

}

What we've done here is to define an interstitial ad and requesting new ad on start of this class. If you need to display Banner ads, you can do it by adding a BannerView variable just like our InterstitialAd variable and requesting an ad for it.

adUnitId
Here we use the ad unit Ids we get when we created the ads in AdMob web page. So just replace the adUnitId variable's value with your ad's unit Id.


Please note that I've called the DontDestroyOnLoad(this.gameObject) method on Awake method because I don't want this AdManager class object to destroy and recreate on every scene loads because we only need a single AdManager object per our game.

When we want to show our ad (for example on game over) we call the ShowAd method of this class. In ShowAd method we check if the ad is active. So we can disable the ad logic temporarily when we test our game in editor.

When creating an ad request, we can add test device Ids so we can test our ads with those devices. This step is important because if you haven't add your test device here, you will receive real ads instead of test ads and this will be nonethical because ad publishers might be charged when their ads displayed. 




Ok. Now return to Unity and add a new GameObject by clicking Create Empty on GameObject menu. And let's name it AdManagerObj. Add AdManager script to this object by clicking Add Component button.



Here, we can enable or disable the ad or we can set the ad cycle. Here I set it to 2 so the ad will be displayed when we call the ShowAd method for the 2nd, 4th, 6th times..

Where and when to call the ShowAd method?


Actually it's up to you. I prefer to call it on game over, before the game over window is shown. So whenever you need to show ad, you can call it like:

GameObject.Find("AdManagerObj").GetComponent<AdManager>().ShowAd();


That's it. I think it's easy to implement because of the AdMob unity plugin.

I hope this tutorial helps.

0 comments:

Post a Comment