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);}
为了更好地控制 BannerView 在屏幕上的位置(而不是采用 AdPosition 值提供的位置),请使用以 x 坐标和 y 坐标为参数的构造函数:
// Create a 320x50 banner views at coordinate (0,50) on screen._bannerView=newBannerView(_adUnitId,AdSize.Banner,0,50);
BannerView 的左上角会放置在传递给构造函数的 x 值和 y 值所确定的位置,原点则是屏幕的左上角。
(可选)创建采用自定义尺寸的横幅广告视图
除了使用 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;}}
[[["易于理解","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"]],["最后更新时间 (UTC):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/)"]]