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");
//