Unity集成AdMob后Banner广告显示消失但区域仍可点击问题求助
在Unity游戏项目中集成AdMob广告后,真机上打开应用时Banner广告仅显示0.5秒就消失,但广告所在区域仍可点击,点击后触发广告行为却无广告展示。该功能在Unity编辑器中运行完全正常,仅真机出现异常。使用的广告管理代码如下:
using UnityEngine; using System.Collections; using GoogleMobileAds.Api; using System.Collections.Generic; public class Banner : MonoBehaviour { private BannerView bannerView; void Start() { // Initialize Google Mobile Ads SDK MobileAds.Initialize(initStatus => { }); // Load and show the banner ad StartCoroutine(ShowBannerWithDelay(3f)); } IEnumerator ShowBannerWithDelay(float delay) { // Wait for the specified amount of time yield return new WaitForSeconds(delay); // Show the banner ad // Create the banner ad at the bottom of the screen bannerView = new BannerView("XXXXXXXXX", AdSize.Banner, AdPosition.Bottom); // Create the ad request AdRequest request = new AdRequest(); bannerView.LoadAd(request); } public void HideBanner() { if (bannerView != null) { // Hide the banner ad bannerView.Hide(); } } void OnDestroy() { // Destroy the banner when the object is destroyed if (bannerView != null) { HideBanner(); bannerView.Destroy(); bannerView = null; // Clean up the reference } } }
解决方案
1. 等待SDK初始化完成后再加载广告
MobileAds.Initialize是异步操作,原代码直接在Start中启动协程加载广告,可能SDK未初始化完成就发起请求,导致广告加载异常。修改初始化逻辑:
void Start() { // 等待SDK初始化完成后再执行广告加载 MobileAds.Initialize(initStatus => { StartCoroutine(ShowBannerWithDelay(3f)); }); }
2. 添加广告事件回调,显式控制显示
原代码未监听广告加载状态,广告默认显示后可能因内部状态异常自动隐藏。添加回调监听,在加载成功后显式调用Show(),同时保留日志方便排查问题:
using System; // 需添加该命名空间用于EventArgs IEnumerator ShowBannerWithDelay(float delay) { yield return new WaitForSeconds(delay); // 先销毁已有Banner实例,避免重复创建冲突 if (bannerView != null) { bannerView.Destroy(); bannerView = null; } // 测试阶段建议使用AdMob官方测试ID,避免账号限制 bannerView = new BannerView("ca-app-pub-3940256099942544/6300978111", AdSize.Banner, AdPosition.Bottom); // 绑定广告事件监听 bannerView.OnAdLoaded += HandleAdLoaded; bannerView.OnAdFailedToLoad += HandleAdFailedToLoad; AdRequest request = new AdRequest.Builder().Build(); bannerView.LoadAd(request); } // 广告加载成功后显式显示 public void HandleAdLoaded(object sender, EventArgs args) { bannerView.Show(); Debug.Log("Banner广告加载成功,已显示"); } // 捕获加载失败原因,方便排查问题 public void HandleAdFailedToLoad(object sender, AdFailedToLoadEventArgs args) { Debug.Log($"Banner广告加载失败: {args.LoadAdError.GetMessage()}"); }
3. 修正生命周期管理,避免意外销毁
在OnDestroy中移除事件监听,防止内存泄漏,同时确保只有一个Banner实例存在:
void OnDestroy() { if (bannerView != null) { // 移除事件监听 bannerView.OnAdLoaded -= HandleAdLoaded; bannerView.OnAdFailedToLoad -= HandleAdFailedToLoad; bannerView.Destroy(); bannerView = null; } }
4. 真机环境排查
- 确认Android/iOS项目已正确配置AdMob的App ID(AndroidManifest.xml/Info.plist)
- 检查真机网络是否正常,能访问AdMob服务器
- 确认AdMob后台无广告展示限制,账号状态正常
内容的提问来源于stack exchange,提问作者Shikeb Khan
相关产品推荐
相关产品推荐

