獎勵廣告

獎勵廣告是使用者可選擇與廣告互動以換取應用程式內獎勵的廣告。本指南說明如何將 AdMob 的獎勵廣告整合至 Unity 應用程式。

閱讀一些客戶成功案例: 個案研究 1個案研究 2

本指南說明如何在 Unity 應用程式中整合獎勵廣告。

必要條件

一律使用測試廣告進行測試

以下程式碼範例包含可用於請求測試廣告的廣告單元 ID。其經過特別設定,為每個請求傳回測試廣告,而非製作實際廣告,因此可以安全使用。

不過,您已在AdMob 網頁介面中註冊應用程式,並建立自己的廣告單元 ID 以用於應用程式,請在開發期間明確將裝置設定為測試裝置

Android

ca-app-pub-3940256099942544/5224354917

iOS

ca-app-pub-3940256099942544/1712485313

初始化 Mobile Ads SDK

載入廣告之前,請呼叫 MobileAds.Initialize(),讓應用程式初始化 Mobile Ads SDK。你只需要設定一次,最好是在應用程式啟動時進行。

using GoogleMobileAds;
using GoogleMobileAds.Api;

public class GoogleMobileAdsDemoScript : MonoBehaviour
{
    public void Start()
    {
        // Initialize the Google Mobile Ads SDK.
        MobileAds.Initialize((InitializationStatus initStatus) =>
        {
            // This callback is called once the MobileAds SDK is initialized.
        });
    }
}

如果您使用中介服務,請等到回呼執行後再載入廣告,這麼做可確保所有中介服務轉接程式都已初始化。

導入作業

整合獎勵廣告的主要步驟如下:

  1. 載入獎勵廣告
  2. [選用] 驗證伺服器端驗證 (SSV) 回呼
  3. 顯示獎勵廣告及獎勵回呼
  4. 監聽獎勵廣告事件
  5. 清除獎勵廣告
  6. 預先載入下一則廣告

載入獎勵廣告

系統會在 RewardedAd 類別上使用靜態 Load() 方法載入獎勵廣告。系統會在完成處理常式中,提供已載入的 RewardedAd 物件做為參數。以下範例說明如何載入 RewardedAd


  // These ad units are configured to always serve test ads.
#if UNITY_ANDROID
  private string _adUnitId = "ca-app-pub-3940256099942544/5224354917";
#elif UNITY_IPHONE
  private string _adUnitId = "ca-app-pub-3940256099942544/1712485313";
#else
  private string _adUnitId = "unused";
#endif

  private RewardedAd _rewardedAd;

  /// <summary>
  /// Loads the rewarded ad.
  /// </summary>
  public void LoadRewardedAd()
  {
      // Clean up the old ad before loading a new one.
      if (_rewardedAd != null)
      {
            _rewardedAd.Destroy();
            _rewardedAd = null;
      }

      Debug.Log("Loading the rewarded ad.");

      // create our request used to load the ad.
      var adRequest = new AdRequest();

      // send the request to load the ad.
      RewardedAd.Load(_adUnitId, adRequest,
          (RewardedAd ad, LoadAdError error) =>
          {
              // if error is not null, the load request failed.
              if (error != null || ad == null)
              {
                  Debug.LogError("Rewarded ad failed to load an ad " +
                                 "with error : " + error);
                  return;
              }

              Debug.Log("Rewarded ad loaded with response : "
                        + ad.GetResponseInfo());

              _rewardedAd = ad;
          });
  }

[選用] 驗證伺服器端驗證 (SSV) 回呼

如果應用程式在伺服器端驗證回呼中需要額外資料,則應使用獎勵廣告的自訂資料功能。獎勵廣告物件上設定的任何字串值都會傳遞至 SSV 回呼的 custom_data 查詢參數。如未設定自訂資料值,SSV 回呼中就不會顯示 custom_data 查詢參數值。

下列程式碼範例示範如何在獎勵廣告載入後,設定 SSV 選項。

// send the request to load the ad.
RewardedAd.Load(_adUnitId, adRequest, (RewardedAd ad, LoadAdError error) =>
{
    // If the operation failed, an error is returned.
    if (error != null || ad == null)
    {
        Debug.LogError("Rewarded ad failed to load an ad with error : " + error);
        return;
    }

    // If the operation completed successfully, no error is returned.
    Debug.Log("Rewarded ad loaded with response : " + ad.GetResponseInfo());

    // Create and pass the SSV options to the rewarded ad.
    var options = new ServerSideVerificationOptions
                          .Builder()
                          .SetCustomData("SAMPLE_CUSTOM_DATA_STRING")
                          .Build()
    ad.SetServerSideVerificationOptions(options);

});

如果您要設定自訂獎勵字串,就必須在顯示廣告前完成指定。

顯示獎勵廣告及獎勵回呼

展示廣告時,您必須提供回呼來處理使用者的獎勵。每次載入時只能顯示廣告一次。請使用 CanShowAd() 方法確認廣告已準備好顯示。

下列程式碼是顯示獎勵廣告的最佳方法。

public void ShowRewardedAd()
{
    const string rewardMsg =
        "Rewarded ad rewarded the user. Type: {0}, amount: {1}.";

    if (rewardedAd != null && rewardedAd.CanShowAd())
    {
        rewardedAd.Show((Reward reward) =>
        {
            // TODO: Reward the user.
            Debug.Log(String.Format(rewardMsg, reward.Type, reward.Amount));
        });
    }
}

監聽獎勵廣告事件

如要進一步自訂廣告行為,您可以在廣告生命週期中捕捉幾項事件,例如開啟、關閉等。請註冊委派代表,以便監聽這些事件,如下所示。

private void RegisterEventHandlers(RewardedAd ad)
{
    // Raised when the ad is estimated to have earned money.
    ad.OnAdPaid += (AdValue adValue) =>
    {
        Debug.Log(String.Format("Rewarded ad paid {0} {1}.",
            adValue.Value,
            adValue.CurrencyCode));
    };
    // Raised when an impression is recorded for an ad.
    ad.OnAdImpressionRecorded += () =>
    {
        Debug.Log("Rewarded ad recorded an impression.");
    };
    // Raised when a click is recorded for an ad.
    ad.OnAdClicked += () =>
    {
        Debug.Log("Rewarded ad was clicked.");
    };
    // Raised when an ad opened full screen content.
    ad.OnAdFullScreenContentOpened += () =>
    {
        Debug.Log("Rewarded ad full screen content opened.");
    };
    // Raised when the ad closed full screen content.
    ad.OnAdFullScreenContentClosed += () =>
    {
        Debug.Log("Rewarded ad full screen content closed.");
    };
    // Raised when the ad failed to open full screen content.
    ad.OnAdFullScreenContentFailed += (AdError error) =>
    {
        Debug.LogError("Rewarded ad failed to open full screen content " +
                       "with error : " + error);
    };
}

清除獎勵廣告

使用 RewardedAd 後,請務必先呼叫 Destroy() 方法,再放置參照:

_rewardedAd.Destroy();

這會通知外掛程式,該物件已無法使用,且可收回物件佔用的記憶體。如未呼叫此方法,可能造成記憶體流失。

預先載入下一則廣告

RewardedAd 是一次性的物件。也就是說,獎勵廣告顯示後就無法再次使用該物件。如要請求其他獎勵廣告,您必須建立新的 RewardedAd 物件。

如要為下一個曝光商機準備獎勵廣告,請在 OnAdFullScreenContentClosedOnAdFullScreenContentFailed 廣告事件發生後預先載入獎勵廣告。

private void RegisterReloadHandler(RewardedAd ad)
{
    // Raised when the ad closed full screen content.
    ad.OnAdFullScreenContentClosed += () =>
    {
        Debug.Log("Rewarded Ad full screen content closed.");

        // Reload the ad so that we can show another as soon as possible.
        LoadRewardedAd();
    };
    // Raised when the ad failed to open full screen content.
    ad.OnAdFullScreenContentFailed += (AdError error) =>
    {
        Debug.LogError("Rewarded ad failed to open full screen content " +
                       "with error : " + error);

        // Reload the ad so that we can show another as soon as possible.
        LoadRewardedAd();
    };
}

其他資源