Unity游戏项目中接入GoogleAdMob
先看效果图
接入测试横幅广告,代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GoogleMobileAds.Api;
using System;
public class GoogleAdMobManager : MonoBehaviour
{
private static GoogleAdMobManager _instance;
public static GoogleAdMobManager Instance
{
get
{
if (_instance == null)
{
// 尝试在场景中找到GoogleAdMobManager实例
_instance = FindObjectOfType<GoogleAdMobManager>();
if (_instance == null)
{
Debug.LogError("GoogleAdMobManager instance not found in the scene!");
}
}
return _instance;
}
}
private void Awake()
{
// 确保不会创建GoogleAdMobManager的多个实例
if (_instance != null && _instance != this)
{
Destroy(gameObject);
return;
}
_instance = this;
DontDestroyOnLoad(gameObject); // 防止在加载新场景时销毁此对象(可选)
}
void Start()
{
MobileAds.Initialize((InitializationStatus initStatus) =>
{
CreateBannerView();
LoadAd();
ListenToAdEvents();
// LoadInterstitialAd();
});
}
// Update is called once per frame
void Update()
{
}
#if UNITY_ANDROID
private string _adUnitId = "ca-app-pub-3940256099942544/6300978111";
#elif UNITY_IPHONE
private string _adUnitId = "ca-app-pub-3940256099942544/2934735716";
#else
private string _adUnitId = "unused";
#endif
BannerView _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)
{
DestroyBannerView();
}
// Create a 320x50 banner at top of the screen
_bannerView = new BannerView(_adUnitId, AdSize.Banner, AdPosition.Top);
}
public void LoadAd()
{
// create an instance of a banner view first.
if(_bannerView == null)
{
CreateBannerView();
}
// create our request used to load the ad.
var adRequest = new AdRequest();
// send the request to load the ad.
Debug.Log("Loading banner ad.");
_bannerView.LoadAd(adRequest);
}
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.");
};
}
public void DestroyBannerView()
{
if (_bannerView != null)
{
Debug.Log("Destroying banner view.");
_bannerView.Destroy();
_bannerView = null;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using GoogleMobileAds.Api;
public class GameMgr : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void OnPlayButtonClick()
{
SceneManager.LoadScene("02-Play");
GoogleAdMobManager.Instance?.DestroyBannerView();
}
public void JumpButtonClick()
{
SceneManager.LoadScene("03-RewardAd");
}
public void OnPauseButtonClick()
{
//暂停广告
//展示广告
LoadInterstitialAd();
}
private InterstitialAd _interstitialAd;
private string _adUnitId = "ca-app-pub-3940256099942544/1033173712";
public void LoadInterstitialAd()
{
if (_interstitialAd != null)
{
_interstitialAd.Destroy();
_interstitialAd = null;
}
Debug.Log("Loading the interstitial ad.");
// InterstitialAd ad = new interstitialAd(_adUnitId);
AdRequest adRequest = new AdRequest();
InterstitialAd.Load(_adUnitId, adRequest,
(InterstitialAd ad, LoadAdError error) =>
{
// if error is not null, the load request failed.
if (error != null || ad == null)
{
Debug.LogError("interstitial ad failed to load an ad " +
"with error : " + error);
return;
}
Debug.Log("Interstitial ad loaded with response : "
+ ad.GetResponseInfo());
_interstitialAd = ad;
});
ShowInterstitialAd();
}
public void ShowInterstitialAd()
{
if (_interstitialAd != null && _interstitialAd.CanShowAd())
{
Debug.Log("Showing interstitial ad.");
_interstitialAd.Show();
}
else
{
Debug.LogError("Interstitial ad is not ready yet.");
}
}
}
场景1,MainCamera上挂载上面两个脚本,GoogleAdMobManager .cs和 GameMgr.cs
创建StartButton按钮
场景2,加载插屏广告InterstitialAd,Main Camera上挂载Game Mgr.cs
创建Pause Game按钮,当暂停的时候,显示插屏广告,调用Game Mgr.cs中OnPauseButtonClick()方法
创建Jump to reward ad,点击跳转到激励广告。点击JumpButton触发GameMgr中JumpButtonClick()方法。
场景2,02-play中的Main Camera上的Audio Listener需去除,项目场景中只能有一个Audio Listener
场景3,加载激励广告
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using GoogleMobileAds.Api;
using System;
public class RewardAd : MonoBehaviour
{
#if UNITY_ANDROID
private string _adUnitId = "ca-app-pub-3940256099942544/5224354917";
#elif UNITY_IPHONE
private string _adUnitId = "ca-app-pub-3940256099942544/1712485313";
#else
private string _adUnitId = "unused";
#endif
private RewardedAd _rewardedAd;
void Start()
{
MobileAds.Initialize((InitializationStatus initStatus) =>
{
LoadRewardedAd();
});
}
public void LoadRewardedAd()
{
// Clean up the old ad before loading a new one.
if (_rewardedAd != null)
{
_rewardedAd.Destroy();
_rewardedAd = null;
}
Debug.Log("Loading the rewarded ad.");
// create our request used to load the ad.
var adRequest = new AdRequest();
// send the request to load the ad.
RewardedAd.Load(_adUnitId, adRequest,
(RewardedAd ad, LoadAdError error) =>
{
// if error is not null, the load request failed.
if (error != null || ad == null)
{
Debug.LogError("Rewarded ad failed to load an ad " +
"with error : " + error);
return;
}
Debug.Log("Rewarded ad loaded with response : "
+ ad.GetResponseInfo());
_rewardedAd = ad;
});
ShowRewardedAd();
}
public void ShowRewardedAd()
{
const string rewardMsg =
"Rewarded ad rewarded the user. Type: {0}, amount: {1}.";
if (_rewardedAd != null && _rewardedAd.CanShowAd())
{
_rewardedAd.Show((Reward reward) =>
{
// TODO: Reward the user.
Debug.Log(String.Format(rewardMsg, reward.Type, reward.Amount));
});
}
}
public void DestroyRewardedAd()
{
if (_rewardedAd != null)
{
Debug.Log("Destroying rewardedAd view.");
_rewardedAd.Destroy();
_rewardedAd = null;
}
}
}