Unity 廣告 API 快速入門


建立時間: 2022年9月29日 00:58
更新時間: 2022年9月29日 20:18

說明

Unity 置入式廣告 API 快速入門教學
目前只提供 iOS 和 Android 插入廣告

我是看最下面參考連結的 Youtube 學的,即使是英文版,觀看時扔相當容易理解
本篇是 Youtube 影片精簡版,如果有任何不懂的地方,請對照影片的內容學習
還有補充一些我遇到的問題,以及解決辦法

大綱

這次教學會完成如下

  1. 遊戲建置設定
  2. 專案設定,打開 Ads 取得 Game Id
  3. 初始化 Unity Ads
  4. 建立獎勵式廣告按鈕
  5. 建立內插式廣告按鈕

什麼是獎勵式、內插式廣告

獎勵式廣告是,當廣告播放完畢後,會呼叫 OnUnityAdsShowComplete 方法
這個方法是要讓你寫獎勵程式用的,例如變比較勇的功能

內插式廣告則看就完事了

1. 遊戲建置設定

打開選單 File -> Build Settings…

build settings

你需要選擇 iOS 或 Android 平台,你需要安裝 iOS 或 Android 模組才能使用
以下是未安裝的畫面

install module

2. 專案設定,打開 Ads 取得 Game Id

打開選單 Window -> General -> Project

create project ID

  1. 按 Ads
  2. 選擇組織
  3. 按 Create project ID (如果已經有的話,改按 Use an existing Unity project ID)

下一步問你,這個 app 是否專門給 13 以下兒童使用,照實回答後按 Save

(圖片省略)

打開 Ads

turn ads

取得 Game Id

get game ID

3. 初始化 Unity Ads

建立 AdsInitializer.cs

程式以官方文件範例為主 Initializing the SDK in Unity

以下是已經完成了實作按鈕,以及我稍微修改過的程式
_interstitialAdsButton, _rewardedAdsButton 都是等等要實作的按鈕
現在先搬到這裡來,等等實作後就不會有錯了

我修改主要有兩點

  1. InitializeAds() 解決在 mac unity play 時,取得非預期的 _gameId
  2. 為了讓範例的按鈕(稍後會說明)可以先關閉,將它們的 Awake() 改到這裡執行
    _*AdUnitId 類型的變數都是給按鈕識別用的,原本都是在後面要說明的腳本才會用上

AdsInitializer.cs

using System;
using UnityEngine;
using UnityEngine.Advertisements;

/**
 * 廣告初始化
 */
public class AdsInitializer : MonoBehaviour, IUnityAdsInitializationListener
{
    // 插頁式廣告按鈕
    [SerializeField] InterstitialAdsButton _interstitialAdsButton;
    // 獎勵廣告按鈕
    [SerializeField] RewardedAdsButton _rewardedAdsButton;
    [SerializeField] bool _testMode = true;
    [SerializeField] string _androidGameId;
    [SerializeField] string _androidInterstitialAdUnitId = "Interstitial_Android";
    [SerializeField] string _androidRewardedAdUnitId = "Rewarded_Android";
    [SerializeField] string _iOSGameId;
    [SerializeField] string _iOSInterstitialAdUnitId = "Interstitial_iOS";
    [SerializeField] string _iOSRewardedAdUnitId = "Rewarded_iOS";
    private string _gameId;
    // This will remain null for unsupported platforms
    public static string InterstitialAdUnitId = null;
    public static string RewardedAdUnitId = null;

    void Awake()
    {
        InitializeAds();
    }

    public void InitializeAds()
    {
        RuntimePlatform[] iosPlatforms = new RuntimePlatform[]
        {
            RuntimePlatform.IPhonePlayer,
            // mac os unity 開發用
            RuntimePlatform.OSXEditor
        };

        /**
         * Get the Ad Unit ID for the current platform:
         */
        if (Array.Exists(iosPlatforms, element => element == Application.platform))
        {
            _gameId = _iOSGameId;
            InterstitialAdUnitId = _iOSInterstitialAdUnitId;
            RewardedAdUnitId = _iOSRewardedAdUnitId;
        }
        else if (Application.platform == RuntimePlatform.Android)
        {
            _gameId = _androidGameId;
            InterstitialAdUnitId = _androidInterstitialAdUnitId;
            RewardedAdUnitId = _androidRewardedAdUnitId;
        }

        Debug.Log($"Application platform: {Application.platform}");
        Advertisement.Initialize(_gameId, _testMode, this);
    }

    public void OnInitializationComplete()
    {
        Debug.Log("Unity Ads initialization complete.");
        // 廣告初始化完成後,載入廣告
        _interstitialAdsButton.LoadAd();
        _rewardedAdsButton.LoadAd();
    }

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

關於應用程式平台

原本的 InitializeAds() 如下

    public void InitializeAds()
    {
        _gameId = (Application.platform == RuntimePlatform.IPhonePlayer)
            ? _iOSGameId
            : _androidGameId;
        Advertisement.Initialize(_gameId, _testMode, this);
    }

在 mac unity play 時 Application.platformOSXEditor
我以為選了 iOS 平台會是 IPhonePlayer,但結果是我大意了
結果我選 iOS 平台 _gameId = _androidGameId 會發生錯誤

所以我修改的版本特別加了 OSXEditor 給 mac unity 用
你的變數可能也會不同,有需要時可以 Debug.Log(Application.platform) 查看

所有平台屬性可參考 RuntimePlatform enumeration

接著建立一個空物件,物件名稱可以自行決定
然後把 Game Id 輸入進去

ads manager

如果你直接複製我的,你會看到多一些屬性,除了按鈕以外其他都可先填上

my ads initializer properties

專案廣告單元

在開始做廣告按鈕之前,先來取得專案廣告單元,就是各種識別廣告的識別號碼

首先先登入 Unity 官網

打開 Dashboard

Dashboard

選擇你的專案

select project at dashboard

選擇 Monetization -> Ad Units
然後按 Complete Activation(因為網頁更新,按鈕名稱有變,請找到那種樣子的按鈕)

Complete Activation

接著選項照實回答,練習時選擇意思接近 only Unity Ads 那個

complete activation options

4. 建立獎勵式廣告按鈕

程式以官方文件範例為主 Implementing rewarded ads in Unity

以下是我稍微修改過的程式
與範例的差異在於 Awake() 的功能移到 AdsInitializer.cs
你可以再回頭看一下 AdsInitializer.cs

RewardedAdsButton.cs

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Advertisements;

/**
 * 獎勵廣告按鈕
 */
public class RewardedAdsButton : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
    [SerializeField] Button _showAdButton;

    void Awake()
    {
    }

    // Load content to the Ad Unit:
    public void LoadAd()
    {
        // IMPORTANT! Only load content AFTER initialization (in this example, initialization is handled in a different script).
        Debug.Log("Loading Ad: " + AdsInitializer.RewardedAdUnitId);
        Advertisement.Load(AdsInitializer.RewardedAdUnitId, this);
    }

    // If the ad successfully loads, add a listener to the button and enable it:
    public void OnUnityAdsAdLoaded(string adUnitId)
    {
        Debug.Log("Ad Loaded: " + adUnitId);

        if (adUnitId.Equals(AdsInitializer.RewardedAdUnitId))
        {
            // Configure the button to call the ShowAd() method when clicked:
            _showAdButton.onClick.AddListener(ShowAd);
            // Enable the button for users to click:
            _showAdButton.interactable = true;
        }
    }

    // Implement a method to execute when the user clicks the button:
    public void ShowAd()
    {
        // Disable the button:
        _showAdButton.interactable = false;
        // Then show the ad:
        Advertisement.Show(AdsInitializer.RewardedAdUnitId, this);
    }

    // Implement the Show Listener's OnUnityAdsShowComplete callback method to determine if the user gets a reward:
    public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState)
    {
        if (adUnitId.Equals(AdsInitializer.RewardedAdUnitId) && showCompletionState.Equals(UnityAdsShowCompletionState.COMPLETED))
        {
            Debug.Log("Unity Ads Rewarded Ad Completed");
            // Grant a reward.
            Debug.Log("You have gained 10 coins");

            // Load another ad:
            Advertisement.Load(AdsInitializer.RewardedAdUnitId, this);
        }
    }

    // Implement Load and Show Listener error callbacks:
    public void OnUnityAdsFailedToLoad(string adUnitId, UnityAdsLoadError error, string message)
    {
        Debug.Log($"Error loading Ad Unit {adUnitId}: {error.ToString()} - {message}");
        // Use the error details to determine whether to try to load another ad.
    }

    public void OnUnityAdsShowFailure(string adUnitId, UnityAdsShowError error, string message)
    {
        Debug.Log($"Error showing Ad Unit {adUnitId}: {error.ToString()} - {message}");
        // Use the error details to determine whether to try to load another ad.
    }

    public void OnUnityAdsShowStart(string adUnitId) { }
    public void OnUnityAdsShowClick(string adUnitId) { }

    void OnDestroy()
    {
        // Clean up the button listeners:
        _showAdButton.onClick.RemoveAllListeners();
    }
}

你可以注意一下,這個按鈕點擊監聽是在程式內實作
_showAdButton.onClick.AddListener(ShowAd)
與內插式廣告按鈕不同,內插式廣告按鈕點擊監聽是在 Inspector 上設定

接著建立一個按鈕,外觀大小依各人喜好調整,主要加上 RewardedAdsButton.cs
然後將 button 組件移到 Show Ad Button
其他兩個打叉的是因為我已經將它們移到 AdsInitializer.cs

rewarded ads button

最後將按鈕移動到 Ads InitializerRewarded Ads Button 屬性

ads initializer set rewarded ads button

測試一下,沒意外的話,按下獎勵廣告按鈕你會看到測試廣告畫面
以及 Console 有一些 Log,理論上不應該出現錯誤訊息

rewarded ads preview

5. 建立內插式廣告按鈕

做法和建立獎勵式廣告按鈕大同小異

程式以官方文件範例為主 Implementing basic ads in Unity

以下是我稍微修改過的程式
與範例的差異在於 Awake() 的功能移到 AdsInitializer.cs
你可以再回頭看一下 AdsInitializer.cs

InterstitialAdsButton.cs

using System;
using UnityEngine;
using UnityEngine.Advertisements;

/**
 * 內插式廣告按鈕
 */
public class InterstitialAdsButton : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
    void Awake()
    {
    }

    // Load content to the Ad Unit:
    public void LoadAd()
    {
        // IMPORTANT! Only load content AFTER initialization (in this example, initialization is handled in a different script).
        Debug.Log("Loading Ad: " + AdsInitializer.InterstitialAdUnitId);
        Advertisement.Load(AdsInitializer.InterstitialAdUnitId, this);
    }

    // Show the loaded content in the Ad Unit:
    public void ShowAd()
    {
        // Note that if the ad content wasn't previously loaded, this method will fail
        Debug.Log("Showing Ad: " + AdsInitializer.InterstitialAdUnitId);
        Advertisement.Show(AdsInitializer.InterstitialAdUnitId, this);
    }

    // Implement Load Listener and Show Listener interface methods: 
    public void OnUnityAdsAdLoaded(string adUnitId)
    {
        // Optionally execute code if the Ad Unit successfully loads content.
    }

    public void OnUnityAdsFailedToLoad(string adUnitId, UnityAdsLoadError error, string message)
    {
        Debug.Log($"Error loading Ad Unit: {adUnitId} - {error.ToString()} - {message}");
        // Optionally execute code if the Ad Unit fails to load, such as attempting to try again.
    }

    public void OnUnityAdsShowFailure(string adUnitId, UnityAdsShowError error, string message)
    {
        Debug.Log($"Error showing Ad Unit {adUnitId}: {error.ToString()} - {message}");
        // Optionally execute code if the Ad Unit fails to show, such as loading another ad.
    }

    public void OnUnityAdsShowStart(string adUnitId) { }
    public void OnUnityAdsShowClick(string adUnitId) { }
    public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState) { }
}

接著建立一個按鈕,外觀大小依各人喜好調整,主要加上 InterstitialAdsButton.cs
然後新增 On Click 事件
其他兩個打叉的是因為我已經將它們移到 AdsInitializer.cs

interstitial ads button on click

最後將按鈕移動到 Ads InitializerInterstitial Ads Button 屬性

ads initializer set interstitial ads button

測試一下,沒意外的話,按下內插式廣告按鈕你會看到測試廣告畫面
以及 Console 有一些 Log,理論上不應該出現錯誤訊息

interstitial preview

參考

觀看次數: 1624
adsadvertisementadvertisingapibuttoninterstitialrewardunity
按讚追蹤 Enjoy 軟體 Facebook 粉絲專頁
每週分享資訊技術

一杯咖啡的力量,勝過千言萬語的感謝。

支持我一杯咖啡,讓我繼續創作優質內容,與您分享更多知識與樂趣!