下列程式碼範例包含廣告單元 ID,可用於要求測試廣告。這類 ID 經特別設定,可針對每項要求傳回測試廣告,而非實際廣告,因此可安心使用。
不過,在 AdMob 網頁介面中註冊應用程式,並建立要在應用程式中使用的廣告單元 ID 後,請在開發期間將裝置明確設為測試裝置。
Android
ca-app-pub-3940256099942544/6300978111
iOS
ca-app-pub-3940256099942544/2934735716
初始化 Mobile Ads SDK
應用程式必須先呼叫 MobileAds.Initialize(),初始化 Mobile Ads SDK 之後,才能載入廣告。這項操作只需執行一次,最佳時機是應用程式啟動時。
usingGoogleMobileAds;usingGoogleMobileAds.Api;publicclassGoogleMobileAdsDemoScript:MonoBehaviour{publicvoidStart(){// Initialize the Google Mobile Ads SDK.MobileAds.Initialize((InitializationStatusinitStatus)=>
{// This callback is called once the MobileAds SDK is initialized.});}}
// These ad units are configured to always serve test ads.#if UNITY_ANDROIDprivatestring_adUnitId="ca-app-pub-3940256099942544/6300978111";#elif UNITY_IPHONEprivatestring_adUnitId="ca-app-pub-3940256099942544/2934735716";#elseprivatestring_adUnitId="unused";#endifBannerView_bannerView;/// <summary>/// Creates a 320x50 banner view at top of the screen./// </summary>publicvoidCreateBannerView(){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=newBannerView(_adUnitId,AdSize.Banner,AdPosition.Top);}
如要用比 AdPosition 值更精確的方式,控管 BannerView 在螢幕上的顯示位置,請使用包含 X 和 Y 座標參數的建構函式:
// Create a 320x50 banner views at coordinate (0,50) on screen._bannerView=newBannerView(_adUnitId,AdSize.Banner,0,50);
系統會以畫面左上角為原點,根據傳入建構函式的 X 與 Y 值,定位 BannerView 左上角的位置。
(選用) 建立自訂大小的橫幅廣告檢視區塊
除了使用 AdSize 常數,您也可以自行指定廣告大小:
// Use the AdSize argument to set a custom size for the ad.AdSizeadSize=newAdSize(250,250);_bannerView=newBannerView(_adUnitId,adSize,AdPosition.Bottom);
載入橫幅廣告
如要載入廣告,請建立 AdRequest 並傳遞至 LoadAd() 方法。
/// <summary>/// Creates the banner view and loads a banner ad./// </summary>publicvoidLoadAd(){// create an instance of a banner view first.if(_bannerView==null){CreateBannerView();}// create our request used to load the ad.varadRequest=newAdRequest();// 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>privatevoidListenToAdEvents(){// 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+=(LoadAdErrorerror)=>
{Debug.LogError("Banner view failed to load an ad with error : "+error);};// Raised when the ad is estimated to have earned money._bannerView.OnAdPaid+=(AdValueadValue)=>
{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>publicvoidDestroyAd(){if(_bannerView!=null){Debug.Log("Destroying banner view.");_bannerView.Destroy();_bannerView=null;}}
大功告成!應用程式可以顯示橫幅廣告了。
重新整理廣告
如已設定廣告單元重新整理功能,廣告載入失敗時,就不需要請求其他廣告。Google Mobile Ads SDK 會套用您在 AdMob UI 指定的重新整理頻率。如果您未啟用重新整理功能,請發出新請求。請參閱「為橫幅廣告使用自動重新整理功能」一文,進一步瞭解廣告單元重新整理功能 (例如設定重新整理頻率)。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-08-28 (世界標準時間)。"],[[["\u003cp\u003eBanner ads are rectangular image or text ads that refresh automatically and are a great starting point for mobile advertising.\u003c/p\u003e\n"],["\u003cp\u003eThis guide provides instructions and code snippets for integrating banner ads into your Unity app.\u003c/p\u003e\n"],["\u003cp\u003eBefore loading ads, initialize the Mobile Ads SDK once at app launch using \u003ccode\u003eMobileAds.Initialize()\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eCreate and load a \u003ccode\u003eBannerView\u003c/code\u003e object with your ad unit ID and preferred size/position to display the ad.\u003c/p\u003e\n"],["\u003cp\u003eCustomize your ad's behavior and release resources by listening to banner view events and calling \u003ccode\u003eDestroy()\u003c/code\u003e when finished.\u003c/p\u003e\n"]]],["This guide details how to integrate banner ads into a Unity app. Key actions include initializing the Mobile Ads SDK, creating a `BannerView` instance with a specified ad unit ID, size, and position, and loading an ad via an `AdRequest`. The guide also covers how to listen to banner ad lifecycle events, such as loading and clicking. It provides instructions on destroying the banner view, and specifies using test ad unit IDs during development. It outlines the usage of various `AdSize` constants for banner ads.\n"],null,["Select platform: [Android](/admob/android/banner \"View this page for the Android platform docs.\") [iOS](/admob/ios/banner \"View this page for the iOS platform docs.\") [Unity](/admob/unity/banner \"View this page for the Unity platform docs.\") [Flutter](/admob/flutter/banner \"View this page for the Flutter platform docs.\")\n\n\u003cbr /\u003e\n\nBanner views are rectangular image or text ads that occupy a spot on screen.\nThey stay on screen while users are interacting with the app, and can refresh\nautomatically after a certain period of time. If you're new to mobile\nadvertising, they're a great place to start.\n\n[Case study](//admob.google.com/home/resources/fingersoft-uses-admob-in-app-purchases-to-make-the-most-of-hill-climb-racing/).\n\n\nThis guide shows you how to integrate banner views into a Unity app. In addition\nto code snippets and instructions, it also includes information about sizing\nbanners properly and links to additional resources.\n\nPrerequisites\n\n- Complete the [Get started guide](/admob/unity/quick-start).\n\nAlways test with test ads\n\nThe following sample code contains an ad unit ID which you can use to request\ntest ads. It's been specially configured to return test ads rather than\nproduction ads for every request, making it safe to use.\n\nHowever, after you've registered an app in the\nAdMob web interface and created your own ad unit\nIDs for use in your app, explicitly [configure your device as a test\ndevice](/admob/unity/test-ads#enable_test_devices) during\ndevelopment. \n\nAndroid\n\n`ca-app-pub-3940256099942544/6300978111`\n\niOS\n\n`ca-app-pub-3940256099942544/2934735716`\n\nInitialize the Mobile Ads SDK\n\nBefore loading ads, have your app initialize Google Mobile Ads SDK by calling\n`MobileAds.Initialize()`. This needs to be done only once, ideally at app launch. \n\n using GoogleMobileAds;\n using GoogleMobileAds.Api;\n\n public class GoogleMobileAdsDemoScript : MonoBehaviour\n {\n public void Start()\n {\n // Initialize Google Mobile Ads SDK.\n MobileAds.Initialize((InitializationStatus initStatus) =\u003e\n {\n // This callback is called once the MobileAds SDK is initialized.\n });\n }\n }\n\nIf you're using mediation, wait until the callback occurs before loading ads as\nthis will ensure that all mediation adapters are initialized.\n\nBannerView example\n\nThe following sample code details how to use the banner view. In the example,\ncreate an instance of a banner view, use an\n`AdRequest` to load an ad into the banner view, and\nthen extend its capabilities by handling lifecycle events.\n\nCreate a banner view\n\nThe first step in using a banner view is to create an instance of a banner view. \n\n // Create a 320x50 banner at top of the screen.\n bannerView = new BannerView(\"\u003cvar translate=\"no\"\u003eAD_UNIT_ID\u003c/var\u003e\", AdSize.Banner, AdPosition.Top); \n https://github.com/googleads/googleads-mobile-unity/blob/9544f919c5c8067939fa38d7fb45d698a7408dc1/samples/HelloWorld/Assets/Snippets/BannerViewSnippets.cs#L23-L24\n\nReplace \u003cvar class=\"readonly\" translate=\"no\"\u003eAD_UNIT_ID\u003c/var\u003e with your ad unit ID.\n\nThe constructor for a `BannerView` has the following\nparameters:\n\n- `adUnitId`: The ad unit ID of the banner ad to load.\n- `AdSize`: The [banner size](#banner_sizes) you'd like to use.\n- `AdPosition`: The position where the banner views should be placed.\n\n| **Note:** ad unit IDs are platform dependent. Use an iOS ad unit for making ad requests on iOS and an Android ad unit ID for making requests on Android.\n\n(Optional) Create a banner view with a custom position\n\nFor greater control over where a banner view is placed on screen than what's\noffered by `AdPosition` values, use the constructor\nthat has x- and y-coordinates as parameters: \n\n // Create a 320x50 banner views at coordinate (0,50) on screen.\n bannerView = new BannerView(\"\u003cvar translate=\"no\"\u003eAD_UNIT_ID\u003c/var\u003e\", AdSize.Banner, 0, 50); \n https://github.com/googleads/googleads-mobile-unity/blob/9544f919c5c8067939fa38d7fb45d698a7408dc1/samples/HelloWorld/Assets/Snippets/BannerViewSnippets.cs#L31-L32\n\nThe top-left corner of the banner view is positioned at the x and y values\npassed to the constructor, where the origin is the top-left of the screen.\n\n(Optional) Create a banner view with a custom size\n\nIn addition to using an `AdSize` constant, you can also specify a custom size\nfor your ad: \n\n // Create a 250x250 banner at the bottom of the screen.\n AdSize adSize = new AdSize(250, 250);\n bannerView = new BannerView(\"\u003cvar translate=\"no\"\u003eAD_UNIT_ID\u003c/var\u003e\", adSize, AdPosition.Bottom); \n https://github.com/googleads/googleads-mobile-unity/blob/9544f919c5c8067939fa38d7fb45d698a7408dc1/samples/HelloWorld/Assets/Snippets/BannerViewSnippets.cs#L39-L41\n\nLoad a banner ad\n\nTo load an ad, create an `AdRequest` and pass it to\nthe `LoadAd()` method. \n\n // Send a request to load an ad into the banner view.\n bannerView.LoadAd(new AdRequest()); \n https://github.com/googleads/googleads-mobile-unity/blob/9544f919c5c8067939fa38d7fb45d698a7408dc1/samples/HelloWorld/Assets/Snippets/BannerViewSnippets.cs#L65-L66\n\n\n| **Tip:** You can use ad load calls to build up a cache of preloaded ads before you intend to show them, so that ads can be shown with zero latency when needed. Since ads expire after an hour, you should clear this cache and reload with new ads every hour.\n\n\u003cbr /\u003e\n\nListen to banner view events\n\nTo customize the behavior of your ad, you can hook into a number of events in\nthe ad's lifecycle, such as loading, opening, or closing. To listen for these\nevents, register a delegate: \n\n bannerView.OnBannerAdLoaded += () =\u003e\n {\n // Raised when an ad is loaded into the banner view.\n };\n bannerView.OnBannerAdLoadFailed += (LoadAdError error) =\u003e\n {\n // Raised when an ad fails to load into the banner view.\n };\n bannerView.OnAdPaid += (AdValue adValue) =\u003e\n {\n // Raised when the ad is estimated to have earned money.\n };\n bannerView.OnAdImpressionRecorded += () =\u003e\n {\n // Raised when an impression is recorded for an ad.\n };\n bannerView.OnAdClicked += () =\u003e\n {\n // Raised when a click is recorded for an ad.\n };\n bannerView.OnAdFullScreenContentOpened += () =\u003e\n {\n // Raised when an ad opened full screen content.\n };\n bannerView.OnAdFullScreenContentClosed += () =\u003e\n {\n // Raised when the ad closed full screen content.\n }; \n https://github.com/googleads/googleads-mobile-unity/blob/9544f919c5c8067939fa38d7fb45d698a7408dc1/samples/HelloWorld/Assets/Snippets/BannerViewSnippets.cs#L73-L100\n\nDestroy the banner view\n\nWhen finished using the banner view, be sure to call `Destroy()` to release\nresources. \n\n if (bannerView != null)\n {\n // Always destroy the banner view when no longer needed.\n bannerView.Destroy();\n bannerView = null;\n } \n https://github.com/googleads/googleads-mobile-unity/blob/9544f919c5c8067939fa38d7fb45d698a7408dc1/samples/HelloWorld/Assets/Snippets/BannerViewSnippets.cs#L107-L112\n\nThat's it! Your app is now ready to display banner ads.\n\nRefresh an ad\n\nIf you configured your ad unit to refresh, you don't need to request another ad\nwhen the ad fails to load. Google Mobile Ads SDK respects any refresh rate\nyou specified in the AdMob UI. If you haven't enabled\nrefresh, issue a new request. For more details on ad unit refresh, such as\nsetting a refresh rate, see\n\n[Use automatic refresh for Banner ads](//support.google.com/admob/answer/3245199).\n\n| **Note:** When setting a refresh rate in the AdMob UI, the automatic refresh occurs only if the banner is visible on screen.\n\nBanner sizes\n\nThe following table lists the standard banner sizes:\n\n| Size in dp (WxH) | Description | Availability | AdSize constant |\n|--------------------------------------|----------------------------------------------------------|--------------------|--------------------|\n| 320x50 | Standard Banner | Phones and Tablets | `BANNER` |\n| 320x100 | Large Banner | Phones and Tablets | `LARGE_BANNER` |\n| 300x250 | IAB Medium Rectangle | Phones and Tablets | `MEDIUM_RECTANGLE` |\n| 468x60 | IAB Full-Size Banner | Tablets | `FULL_BANNER` |\n| 728x90 | IAB Leaderboard | Tablets | `LEADERBOARD` |\n| *Provided width* x *Adaptive height* | [Adaptive banner](/admob/unity/banner/anchored-adaptive) | Phones and Tablets | N/A |\n| *Screen width* x 32\\|50\\|90 | [Smart banner](/admob/unity/banner/smart) | Phones and Tablets | `SMART_BANNER` |\n| Learn more about [Adaptive Banners](/admob/unity/banner/anchored-adaptive), intended to replace [Smart Banners](/admob/unity/banner/smart). ||||\n\n| **Note:** If an Android app tries to load a banner that's too big for its layout, the SDK won't display it, logging an error message instead.\n\nAdditional resources\n\n- [HelloWorld example](//github.com/googleads/googleads-mobile-unity/tree/main/samples/HelloWorld): A minimal implementation of all ad formats.\n\n\u003c!-- --\u003e\n\n- [Sample use\n case](//admob.google.com/home/resources/fingersoft-uses-admob-in-app-purchases-to-make-the-most-of-hill-climb-racing/)"]]