Skip to main content

How to use Unity Ads in your mobile game (2024)

If you are developing with Unity Engine and planning to publish a mobile game, including ads is a great way to monetize it and make money with it. This is quite easy to do with the Unity Ads SDK. In this post I will explain the process step by step to integrate Unity Ads into your game and start making revenue out of your development.

How does Unity advertisement work?

First, I'll quickly explain how everything works under the hood with Unity Ads. There are three basic steps that need to happen for an ad to show in your game:
  • Initializing ads: this happens every time the game launches.
  • Loading ads: this is when the ads load from the server and it happens always before showing an ad.
  • Showing the ads: this is when the actual advertisement is shown to the user.
Why is this important? Because loading an ad can take some time, just like loading a video in Youtube. If you try to load the ad right before showing it, in some cases, it can take longer than usual which could lead to skipping the ad. That is something we don't want as it will translate into a drop in fill rate -> less profit. It could also lead to other strange behaviors we want to avoid. For this reason, the strategy we will follow is loading the ad as soon as possible before actually showing it. This could be implemented by loading the ad right after the game is launched and then loading again right after the ad is shown. This will give time for the ads to load and maybe even retry failed loading operations.

The other thing you need to know is there are three kinds of ads you can insert into your game depending on your advertisement placement strategy. You might already be familiar with them:
  1. Banner ads: This ads display in the form of a banner in a fixed position of the screen. When clicked, the banner contains a link to the advertised product.
  2. Interstitial ads: These ads display in the form of videos. You can decide when to play them. Normally, they are shown at specific moments of the gameplay, for example, after losing the game.
  3. Rewarded ads: They are almost the same as interstitial ads, instead this ones are used to reward the player after watching them. For example, you can reward in-game coins.

Setting up your Unity project

Setting up your project for Unity Ads is pretty simple. Once in the Unity Editor and with your project loaded, click Edit > Project Settings > Services. In this Window, if we haven't previously generated a project ID, we will create it by selecting an organization and clicking "Create new cloud project and link to Unity project".


Once you have created the Unity Cloud project, you will see the general information and the option to select whether your game is targeted to children under 13. Unless you are really sure you are targeting young audiences, make sure you select "no" to avoid complications. Then click "Save".


Now you can click "Dashboard" to go to https://cloud.unity.com/ and access your project page, where you will go to Unity Ads Monetization in the left. If you don't see it, you can add the shortcut with the + button.


Click "Get started" > "I only plan to use Unity Ads" > "No, I want to start fresh".





And in case your app is not live yet on any app store, select "My app is not live in an app store yet". In other case, paste your URL to any of the stores. Then you are ready to click "Add project". You will see your project IDs. Don't worry, we can grab them later when needed. For now, click "Finish".


Now, if we click on "Ad units" in the left menu, we will be able to see the project IDs and the IDs for each of the ad units we will need later when coding.


The last thing we will need to do in order to set up our project is installing the Unity Ads SDK. In the editor, we will open the Package Manager window (Window > Package Manager) and in the "Packages:" drop down selection make sure to pick "Unity Registry".


Here we will scroll down in the left and select "Advertisement Legacy". You can also use the search bar (top right corner).


Now click "Install", wait for it to complete and we're ready to go!

Coding the ads into your game

With everything set up, we are now ready to code the advertisements into our game. It is easier than it might seem. By the way, everything I will show here can also be found in the official documentation.

I recommend creating a specific folder to keep all your advertisement scripts together. Now, we will go one by one. You can copy and paste the code, then adapt it to your project.

AdsInitializer.cs

This script will be in charge of initializing the ads right after launching the game.

using UnityEngine;
using UnityEngine.Advertisements;

public class AdsInitializer : MonoBehaviour, IUnityAdsInitializationListener
{
    
    [SerializeField] string _androidGameId;
    [SerializeField] string _iOSGameid;
    [SerializeField] bool _testMode = true;
    private string _gameId;

    void Awake(){
        InitializeAds();
    }

    public void InitializeAds(){
        #if UNITY_IOS
            _gameId = _iOSGameId;
        #elif UNITY_ANDROID
            _gameId = _androidGameId;
        #elif UNITY_EDITOR
            _gameId = _androidGameId; //Only for testing the functionality in the Editor
        #endif

        if (!Advertisement.isInitialized && Advertisement.isSupported)
        {
            Advertisement.Initialize(_gameId, _testMode, this);
        }
    }

    public void OnInitializationComplete()
    {
        Debug.Log("Unity Ads initialization complete.");
    }
 
    public void OnInitializationFailed(UnityAdsInitializationError error, string message)
    {
        Debug.Log($"Unity Ads Initialization Failed: {error.ToString()} - {message}");
    }
}

BannerAds.cs

This class implements the functionality for banner type ads.

using UnityEngine;
using UnityEngine.Advertisements;

public class BannerAds : MonoBehaviour
{
    [SerializeField] string androidAdUnitId;
    [SerializeField] string iosAdUnitId;

    private string adUnitId;

    void Awake(){
        #if UNITY_IOS
            adUnitId = iosAdUnitId;
        #elif UNITY_ANDROID
            adUnitId = androidAdUnitId;
        #endif

        Advertisement.Banner.SetPosition(BannerPosition.BOTTOM_CENTER);
    }

    public void LoadBannerAd(){
        BannerLoadOptions options = new BannerLoadOptions{
            loadCallback = BannerLoaded,
            errorCallback = BannerLoadedError
        };

        Advertisement.Banner.Load(adUnitId, options);
    }

    public void ShowBannerAd(){
        BannerOptions options = new BannerOptions{ 
            showCallback = BannerShown,
            clickCallback = BannerClicked,
            hideCallback = BannerHidden
        };

        Advertisement.Banner.Show(adUnitId, options);
    }

    public void HideBannerAd(){
        Advertisement.Banner.Hide();
    }

    private void BannerLoaded(){
        Debug.Log("Banner loaded");
    }

    private void BannerLoadedError(string message){
        Debug.Log("Error while loading banner");
    }

    private void BannerHidden() {}

    private void BannerClicked() {}

    private void BannerShown() {}
}

InterstitialAds.cs

This one is for interstitial ads as you might have guessed.

using UnityEngine;
using UnityEngine.Advertisements;

public class InterstitialAds : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
    [SerializeField] string androidAdUnitId;
    [SerializeField] string iosAdUnitId;

    private string adUnitId;

    void Awake(){
        #if UNITY_IOS
            adUnitId = iosAdUnitId;
        #elif UNITY_ANDROID
            adUnitId = androidAdUnitId;
        #endif
    }
    
    public void LoadInterstitialAd(){
        Advertisement.Load(adUnitId, this);
    }

    public void ShowInterstitialAd(){
        Advertisement.Show(adUnitId, this);
        LoadInterstitialAd();
    }

    public void OnUnityAdsAdLoaded(string placementId)
    {
        Debug.Log("Interstitial ad loaded");
    }

    public void OnUnityAdsFailedToLoad(string placementId, UnityAdsLoadError error, string message)
    {
        Debug.Log("Failed to load interstitial ad");
        LoadInterstitialAd(); // To retry in case of loading failure
    }

    public void OnUnityAdsShowFailure(string placementId, UnityAdsShowError error, string message)
    {
        AdsManager.Instance.bannerAds.ShowBannerAd();
    }

    public void OnUnityAdsShowStart(string placementId)
    {
        throw new System.NotImplementedException();
    }

    public void OnUnityAdsShowClick(string placementId)
    {
        throw new System.NotImplementedException();
    }

    public void OnUnityAdsShowComplete(string placementId, UnityAdsShowCompletionState showCompletionState)
    {
        throw new System.NotImplementedException();
    }
}

RewardedAds.cs

And this one for rewarded ads. In this case, make sure you implement the reward in the OnUnityAdsShowComplete callback.

using UnityEngine;
using UnityEngine.Advertisements;

public class RewardedAds : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
    [SerializeField] string androidAdUnitId;
    [SerializeField] string iosAdUnitId;

    private string adUnitId;

    void Awake(){
        #if UNITY_IOS
            adUnitId = iosAdUnitId;
        #elif UNITY_ANDROID
            adUnitId = androidAdUnitId;
        #endif
    }

    public void LoadRewardedAd(){
        Advertisement.Load(adUnitId, this);
    }

    public void ShowRewardedAd(){
        Advertisement.Show(adUnitId, this);
        LoadRewardedAd();
    }

    public void OnUnityAdsAdLoaded(string placementId)
    {
        Debug.Log("Rewarded ad loaded");
    }

    public void OnUnityAdsFailedToLoad(string placementId, UnityAdsLoadError error, string message)
    {
        Debug.Log("Failed to load rewarded ad");
        LoadRewardedAd();
    }

    public void OnUnityAdsShowFailure(string placementId, UnityAdsShowError error, string message)
    {
        AdsManager.Instance.bannerAds.ShowBannerAd();
    }

    public void OnUnityAdsShowStart(string placementId)
    {
        throw new System.NotImplementedException();
    }

    public void OnUnityAdsShowClick(string placementId)
    {
        throw new System.NotImplementedException();
    }

    public void OnUnityAdsShowComplete(string placementId, UnityAdsShowCompletionState showCompletionState)
    {
        if (placementId == adUnitId && showCompletionState.Equals(UnityAdsShowCompletionState.COMPLETED)){
            Debug.Log("Reward granted");
            // Place your reward code here i.e. Resources.Instance.AddCoins(10);
        }
    }
}

AdsManager.cs

The last thing we will need is a manager for our ads within the game. This script will act as the main controller following a singleton pattern. This means it will be attached to a component in the first scene of the game and will exist as a unique instance that is never destroyed when changing scenes. The functionality it will have is very simple:

using UnityEngine;

public class AdsManager : MonoBehaviour
{
    public AdsInitializer adsInitializer;
    public InterstitialAds interstitialAds;
    public RewardedAds rewardedAds;
    public BannerAds bannerAds;

    public static AdsManager Instance {get; private set;}

    void Awake(){
        if(Instance != null && Instance != this){
            Destroy(gameObject);
            return;
        }

        Instance = this;
        DontDestroyOnLoad(gameObject);

        // Load different ad units
        bannerAds.LoadBannerAd();
        interstitialAds.LoadInterstitialAd();
        rewardedAds.LoadRewardedAd();
    }
}

Including the scripts in the scene

Now that we have the necessary scripts, we can include them in our game scene. Follow this simple steps (I will provide a screenshot with the result):
  1. Create an empty game object in the hierarchy and name it AdsManager.
  2. Attach all of the scripts to this newly created game object. We will be working on them from here.
  3. In the inspector, drag each of the scripts for the ads (BannerAds, InterstitialAds and RewardedAds) to their respective instances in the AdsManager script.
  4. Copy the game IDs from the Ad units page in Unity Dashboard into their corresponding place in the AdsInitializer script. Make sure the check box for Test Mode is checked until you are ready for the final build.
  5. Copy each of the ad unit IDs into their corresponding scripts as shown in the image below.

For more detail:


Showing ads wherever we want in our code

Now we have everything set up to show ads in our game. The only remaining thing to do is to decide when to show the ads and making the calls withing our game code.

For example, by adding this to your main game manager you can display the banner ad at the beginning of the game:

using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance {get; private set;}

    void Awake(){
        if(Instance != null && Instance != this){
            Destroy(gameObject);
            return;
        }
        Instance = this;
        DontDestroyOnLoad(gameObject);

        StartCoroutine(DisplayBannerWithDelay());
    }

    private IEnumerator DisplayBannerWithDelay(){
        yield return new WaitForSeconds(1f);
        AdsManager.Instance.bannerAds.ShowBannerAd();
    }

There is a reason why I placed this specific example. I wanted to show that it is necessary to use a coroutine and a delay when showing the banner in the game Awake method because in other case, there will be an error and the banner will never be shown. 

Taking this into consideration, thanks to the fact that the AdsManager is a singleton instance, you can show ads anywhere else in your code with these calls:

AdsManager.Instance.bannerAds.ShowBannerAd(); // Show the banner
AdsManager.Instance.bannerAds.HideBannerAd(); // Hide the banner

AdsManager.Instance.interstitialAds.ShowInterstitialAd(); // Show an interstitial ad

AdsManager.Instance.rewardedAds.ShowRewardedAd(); // Show a rewarded ad. 
//Remember to implement the reward in RewardedAds.cs!

Preparing for the final build and release

Now you have everything ready to show ads in your game. Congratulations! When it's time to publish, you will need to follow these last steps:
  1. Uncheck the Test Mode check box in the Ads Manager.
  2. If you are publishing in Google Play (if not, skip to step 5), once you have the application set up in Google Play, go to the Google Play Console, select the project, scroll down the left menu and go to "Monetization Setup". There, copy the license key.
  3. Go to the Unity dashboard, select your project and go to the settings:
  4. Paste the Google License Key in the Google License Key section:
  5. Go back to Unity Ads Monetization and select "Settings":
  6. Go to Store IDs and paste the store URL to your game:




And that's it! You have all the basic Unity Ads configuration done. I hope this guide helped you achieve the result and you could manage to implement advertisements to monetize your game. If you have any questions, feel free to use the comments section.

Thanks for reading!




Comments