橫幅廣告

橫幅廣告觀看次數是佔據畫面上的位置的矩形圖片或文字廣告。 使用者與應用程式互動時,它們會留在螢幕上,並且會在一段時間後自動重新整理。如果您是第一次使用行動廣告,不妨從這裡著手。

本指南說明如何將橫幅檢視畫面整合至 Unity 應用程式。除了程式碼片段和操作說明外,頁面內還會提供如何正確調整橫幅廣告大小的相關資訊,以及其他資源的連結。

必要條件

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

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

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

/6499/example/banner

初始化 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.
        });
    }
}

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

BannerView 範例

以下程式碼範例詳細說明如何使用橫幅檢視畫面。在此範例中,您要建立橫幅檢視畫面的例項,使用 AdManagerAdRequest 將廣告載入橫幅檢視畫面,然後處理生命週期事件來擴充其功能。

建立橫幅檢視畫面

使用橫幅檢視畫面的第一步,是在與 GameObject 附加的 C# 指令碼中建立橫幅檢視畫面的例項。


  // This ad unit is configured to always serve test ads.
  private string _adUnitId = "/6499/example/banner";

  AdManagerBannerView _bannerView;

  /// <summary>
  /// Creates a 320x50 banner view at top of the screen.
  /// </summary>
  public void CreateBannerView()
  {
      Debug.Log("Creating banner view");

      // If we already have a banner, destroy the old one.
      if (_bannerView != null)
      {
          DestroyAd();
      }

      // Create a 320x50 banner at top of the screen
      _bannerView = new AdManagerBannerView(_adUnitId, AdSize.Banner, AdPosition.Top);
  }

AdManagerBannerView 的建構函式包含下列參數:

  • adUnitIdAdManagerBannerView 應從中載入廣告的廣告單元 ID。
  • AdSize:要使用的廣告大小。詳情請參閱橫幅廣告大小
  • AdPosition:應放置橫幅檢視畫面的位置。AdPosition 列舉列出有效的廣告排序值。

請注意不同平台使用不同廣告單元的方式。您必須使用 iOS 廣告單元,在 iOS 上提出廣告請求;在 Android 上提出廣告請求時,則需使用 Android 廣告單元。

(選用) 建立包含自訂位置的橫幅檢視畫面

如要進一步控制 AdManagerBannerView 在畫面上的位置,而非 AdPosition 值所提供的位置,請使用含有 x 和 y 座標的建構函式做為參數:

// Create a 320x50 banner views at coordinate (0,50) on screen.
_bannerView = new AdManagerBannerView(_adUnitId, AdSize.Banner, 0, 50);

AdManagerBannerView 的左上角位於傳遞至建構函式的 x 和 y 值,其中起點是畫面的左上角。

(選用) 建立自訂大小的橫幅檢視畫面

除了使用 AdSize 常數之外,您還可以為廣告指定自訂大小:

// Use the AdSize argument to set a custom size for the ad.
AdSize adSize = new AdSize(250, 250);
_bannerView = new AdManagerBannerView(_adUnitId, adSize, AdPosition.Bottom);

(選用) 多種廣告大小

Ad Manager 可讓您指定多個可在 AdManagerBannerView 中放送的廣告大小。在 SDK 中導入這項功能前,請先建立指定相同廣告單元,指定與不同大小廣告素材相關聯的委刊項。

在應用程式中將多個 AdSize 參數傳遞至 ValidAdSizes

var adView = new AdManagerBannerView(_adUnitId, AdSize.Banner, AdPosition.Top);
adView.ValidAdSizes = new List<AdSize>
{
    AdSize.Banner, new AdSize(120, 20), new AdSize(250, 250),
};

如果 AdManagerAdView 在重新整理時變更大小,版面配置應該就能自動根據新的大小進行調整。AdManagerAdView 預設為在第一個參數中傳遞的大小,直到下一個廣告傳回為止。

載入橫幅廣告

AdManagerBannerView 設定完畢後,請繼續在 AdManagerBannerView 類別中使用 LoadAd() 方法載入廣告。這個方法可使用 AdManagerAdRequest 參數儲存執行階段資訊,例如指定目標資訊、排除標籤,以及發布商提供的 ID。

/// <summary>
/// Creates the banner view and loads a banner ad.
/// </summary>
public void LoadAd()
{
    // create an instance of a banner view first.
    if(_bannerView == null)
    {
        CreateAdManagerBannerView();
    }

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

    // send the request to load the ad.
    Debug.Log("Loading banner ad.");
    _bannerView.LoadAd(adRequest);
}

監聽橫幅瀏覽事件

如要自訂廣告行為,您可以掛接廣告生命週期中的多個事件,例如載入、開啟或關閉。如要監聽這些事件,請註冊委派代表:

/// <summary>
/// listen to events the banner view may raise.
/// </summary>
private void ListenToAdEvents()
{
    // Raised when an ad is loaded into the banner view.
    _bannerView.OnBannerAdLoaded += () =>
    {
        Debug.Log("Banner view loaded an ad with response : "
            + _bannerView.GetResponseInfo());
    };
    // Raised when an ad fails to load into the banner view.
    _bannerView.OnBannerAdLoadFailed += (LoadAdError error) =>
    {
        Debug.LogError("Banner view failed to load an ad with error : "
            + error);
    };
    // Raised when the ad is estimated to have earned money.
    _bannerView.OnAdPaid += (AdValue adValue) =>
    {
        Debug.Log(String.Format("Banner view paid {0} {1}.",
            adValue.Value,
            adValue.CurrencyCode));
    };
    // Raised when an impression is recorded for an ad.
    _bannerView.OnAdImpressionRecorded += () =>
    {
        Debug.Log("Banner view recorded an impression.");
    };
    // Raised when a click is recorded for an ad.
    _bannerView.OnAdClicked += () =>
    {
        Debug.Log("Banner view was clicked.");
    };
    // Raised when an ad opened full screen content.
    _bannerView.OnAdFullScreenContentOpened += () =>
    {
        Debug.Log("Banner view full screen content opened.");
    };
    // Raised when the ad closed full screen content.
    _bannerView.OnAdFullScreenContentClosed += () =>
    {
        Debug.Log("Banner view full screen content closed.");
    };
}

刪除橫幅檢視畫面

使用橫幅檢視畫面後,請務必呼叫 Destroy() 來釋出資源。

/// <summary>
/// Destroys the banner view.
/// </summary>
public void DestroyBannerView()
{
    if (_bannerView != null)
    {
        Debug.Log("Destroying banner view.");
        _bannerView.Destroy();
        _bannerView = null;
    }
}

大功告成!您的應用程式現在可以顯示橫幅廣告了。

下表列出標準橫幅廣告大小。

大小 (以 dp 為單位,寬 x 高) 說明 適用國家/地區 AdSize 常數
320 x 50 標準橫幅廣告 手機和平板電腦 BANNER
320x100 大型橫幅廣告 手機和平板電腦 LARGE_BANNER
300 x 250 IAB 中矩形廣告 手機和平板電腦 MEDIUM_RECTANGLE
468x60 IAB 全橫幅廣告 平板電腦 FULL_BANNER
728x90 IAB 超級橫幅廣告 平板電腦 LEADERBOARD
提供寬度 x 自動調整高度 自動調整橫幅廣告 手機和平板電腦 不適用
螢幕寬度 x 32|50|90 智慧型橫幅廣告 手機和平板電腦 SMART_BANNER
進一步瞭解旨在取代智慧型橫幅廣告自動調整橫幅廣告

應用程式事件

使用應用程式事件,您就能建立可傳送訊息至應用程式程式碼的廣告。然後,應用程式即可根據這些訊息採取行動。

您可以使用 AppEvent 監聽 Ad Manager 專屬應用程式事件。這些事件可能會在廣告生命週期中隨時發生,即使在呼叫載入前也是如此。

namespace GoogleMobileAds.Api.AdManager;

/// The App event message sent from the ad.
public class AppEvent
{
    // Name of the app event.
    string Name;
    // Argument passed from the app event.
    string Value;
}

廣告發生應用程式事件時,會引發 OnAppEventReceived。以下範例說明如何在程式碼中處理這個事件:

_bannerview.OnAppEventReceived += (AppEvent args) =>
{
    Debug.Log($"Received app event from the ad: {args.Name}, {args.Value}.");
};

以下範例說明如何根據含有顏色名稱的應用程式事件,變更應用程式背景顏色:

_bannerview.OnAppEventReceived += (AppEvent args) =>
{
  if (args.Name == "color")
  {
    Color color;
    if (ColorUtility.TryParseColor(arg.Value, out color))
    {
      gameObject.GetComponent<Renderer>().material.color = color;
    }
  }
};

以下是傳送顏色應用程式事件的對應廣告素材:

<html>
<head>
  <script src="//www.gstatic.com/afma/api/v1/google_mobile_app_ads.js"></script>
  <script>
    document.addEventListener("DOMContentLoaded", function() {
      // Send a color=green event when ad loads.
      admob.events.dispatchAppEvent("color", "green");

      document.getElementById("ad").addEventListener("click", function() {
        // Send a color=blue event when ad is clicked.
        admob.events.dispatchAppEvent("color", "blue");
      });
    });
  </script>
  <style>
    #ad {
      width: 320px;
      height: 50px;
      top: 0px;
      left: 0px;
      font-size: 24pt;
      font-weight: bold;
      position: absolute;
      background: black;
      color: white;
      text-align: center;
    }
  </style>
</head>
<body>
  <div id="ad">Carpe diem!</div>
</body>
</html>

其他資源