# 在 Unity 中实现横幅广告

> 在 Unity 项目中实现横幅广告。加载广告内容，并通过 C# 脚本在屏幕上的固定位置展示广告。

> **Note:**
>
> 从 SDK 4.4.1 版开始，Unity Ads 包在 Unity 编辑器中已更名为 Advertisement Legacy 包。
> Advertisement Legacy 包 4.12 版仍能正常工作，但不会收到任何关于新功能或增强功能的进一步更新。
> SDK 4.12 版支持 Apple 隐私清单更新，无计划对该包进一步更新。

> **Important:**
>
> app-ads.txt 是一个 IAB 倡议文件，旨在打击欺诈，建立透明的广告生态系统。请务必按照要求实现 app-ads.txt。否则，横幅广告需求可能会显著下降。

## 脚本实现##script-implementation

在脚本标头中，声明包含 [`Banner`](/grow/ads/unity-sdk/unity-api.md#banner) 类的 `UnityEngine.Advertisements` 命名空间。接下来，初始化 SDK，然后使用 [`Banner.Load`](/grow/ads/unity-sdk/unity-api.md#banner-load) 和 [`Banner.Show`](/grow/ads/unity-sdk/unity-api.md#banner-show) 方法来加载和展示横幅广告。

以下示例脚本向您展示了如何在场景中设置按钮以测试此功能。要在 Unity 编辑器中创建按钮，请选择 **Game Object（游戏对象）**> **UI** > **Button（按钮）**。

> **Note:**
>
> 请仅在 SDK 初始化后加载内容，否则脚本将无法工作。在此示例中，初始化在另一个脚本中处理。

### 横幅广告示例##banner-ad-example

1. **C#**

   ```cs
   using UnityEngine;
   using UnityEngine.UI;
   using UnityEngine.Advertisements;

   public class BannerAdExample : MonoBehaviour
   {
     // For the purpose of this example, these buttons are for functionality testing:
     [SerializeField] Button _loadBannerButton;
     [SerializeField] Button _showBannerButton;
     [SerializeField] Button _hideBannerButton;

     [SerializeField] BannerPosition _bannerPosition = BannerPosition.BOTTOM_CENTER;

     [SerializeField] string _androidAdUnitId = "Banner_Android";
     [SerializeField] string _iOSAdUnitId = "Banner_iOS";
     string _adUnitId = null; // This will remain null for unsupported platforms.

     void Start()
     {
       // Get the Ad Unit ID for the current platform:
       #if UNITY_IOS
       _adUnitId = _iOSAdUnitId;
       #elif UNITY_ANDROID
       _adUnitId = _androidAdUnitId;
       #endif

       // Disable the button until an ad is ready to show:
       _showBannerButton.interactable = false;
       _hideBannerButton.interactable = false;

       // Set the banner position:
       Advertisement.Banner.SetPosition(_bannerPosition);

       // Configure the Load Banner button to call the LoadBanner() method when clicked:
       _loadBannerButton.onClick.AddListener(LoadBanner);
       _loadBannerButton.interactable = true;
     }

     // Implement a method to call when the Load Banner button is clicked:
     public void LoadBanner()
     {
         // Set up options to notify the SDK of load events:
         BannerLoadOptions options = new BannerLoadOptions
         {
             loadCallback = OnBannerLoaded,
             errorCallback = OnBannerError
         };

         // Load the Ad Unit with banner content:
         Advertisement.Banner.Load(_adUnitId, options);
     }

     // Implement code to execute when the loadCallback event triggers:
     void OnBannerLoaded()
     {
         Debug.Log("Banner loaded");

         // Configure the Show Banner button to call the ShowBannerAd() method when clicked:
         _showBannerButton.onClick.AddListener(ShowBannerAd);
         // Configure the Hide Banner button to call the HideBannerAd() method when clicked:
         _hideBannerButton.onClick.AddListener(HideBannerAd);

         // Enable both buttons:
         _showBannerButton.interactable = true;
         _hideBannerButton.interactable = true;     
     }

     // Implement code to execute when the load errorCallback event triggers:
     void OnBannerError(string message)
     {
         Debug.Log($"Banner Error: {message}");
         // Optionally execute additional code, such as attempting to load another ad.
     }

     // Implement a method to call when the Show Banner button is clicked:
     void ShowBannerAd()
     {
         // Set up options to notify the SDK of show events:
         BannerOptions options = new BannerOptions
         {
             clickCallback = OnBannerClicked,
             hideCallback = OnBannerHidden,
             showCallback = OnBannerShown
         };

         // Show the loaded Banner Ad Unit:
         Advertisement.Banner.Show(_adUnitId, options);
     }

     // Implement a method to call when the Hide Banner button is clicked:
     void HideBannerAd()
     {
         // Hide the banner:
         Advertisement.Banner.Hide();
     }

     void OnBannerClicked() { }
     void OnBannerShown() { }
     void OnBannerHidden() { }

     void OnDestroy()
     {
         // Clean up the listeners:
         _loadBannerButton.onClick.RemoveAllListeners();
         _showBannerButton.onClick.RemoveAllListeners();
         _hideBannerButton.onClick.RemoveAllListeners();
     }
   }
   ```

## 横幅广告位置##banner-position

默认情况下，横幅广告显示画面锚定在屏幕底部中心位置，支持 320 x 50 或 728 x 90 像素分辨率。要指定横幅广告锚点，请使用 `Banner.SetPosition` API。例如：

```cs
Advertisement.Banner.SetPosition (BannerPosition.TOP_CENTER);
```

**后续步骤**：查看[变现策略](/grow/ads/monetization-strategy.md)指南并[测试您的实现](/grow/ads/optimization/test-ads-integration.md)。
