Unity Integrate Admob Tutorial

Unity Integrate Admob Tutorial Code

using UnityEngine;
using GoogleMobileAds.Api;
using System;
using System.Collections.Generic;
using Unity.VisualScripting;

public class AdsAdmob : MonoBehaviour
{
    private Dictionary<string, double> adValues;
    [SerializeField] List<string> adBannerIds;
    [SerializeField] List<string> adInsterIds;
    [HideInInspector]
    public Action sdkStartedEvent;
    [HideInInspector]
    public Action bannerAdsLoadedEvent;
    [HideInInspector]
    public Action insterAdsLoadedEvent;
    public Action InsterAdsShowCompletedEvent;
    public static AdsAdmob _this;
    private int insterAdsIndex;
    private int bannerAdsIndex;
    AdsManager.BannerPos bannerPos;
    BannerView _bannerView;
    private InterstitialAd _interstitialAd;
    void Awake()
    {
        _this = this;
        DontDestroyOnLoad(this);
    }

    void Start()
    {
 
    }

    public void OnCompletedConsentEvent()
    {
        Debug.Log("OnCompletedConsentEvent");
        ConsentManager._this.completedConsentEvent -= OnCompletedConsentEvent;
        if (sdkStartedEvent != null) sdkStartedEvent();
        // Tạo các yêu cầu quảng cáo
        LoadIntersAd();
    }

    // INSTER ADS

    public void ShowInterstitialAd()
    {
        if (_interstitialAd != null && _interstitialAd.CanShowAd())
        {
            Debug.Log("Showing interstitial ad.");
            _interstitialAd.Show();
        }
        else
        {
            LoadIntersAd();
            Debug.LogError("Interstitial ad is not ready yet.");
        }
    }

    // Load Inster Ads

    void LoadIntersAd()
    {
        if (adInsterIds.Count == 0) return;
        insterAdsIndex = adInsterIds.Count - 1;
        string adUnitId = adInsterIds[insterAdsIndex];
        LoadInterstitialAdWithId(adUnitId);
    }

    void LoadInterstitialAdWithId(string adId)
    {
        // Clean up the old ad before loading a new one.
        if (_interstitialAd != null)
        {
            _interstitialAd.Destroy();
            _interstitialAd = null;
        }

        Debug.Log("Loading the interstitial ad.");

        // create our request used to load the ad.
        var adRequest = new AdRequest();

        // send the request to load the ad.
        InterstitialAd.Load(adId, 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);
                    if (insterAdsIndex > 0)
                    {
                        insterAdsIndex--;
                        string adUnitId = adInsterIds[insterAdsIndex];
                        LoadInterstitialAdWithId(adUnitId);
                    }

                }

                Debug.Log("Interstitial ad loaded with response : "
                          + ad.GetResponseInfo());
                if (insterAdsLoadedEvent != null)
                {
                    insterAdsLoadedEvent();
                    Debug.Log("Interstitial ad insterAdsLoadedEvent");
                }
                _interstitialAd = ad;
                RegisterEventHandlers(_interstitialAd);


            });
    }

    private void RegisterEventHandlers(InterstitialAd interstitialAd)
    {
        // Raised when the ad is estimated to have earned money.
        interstitialAd.OnAdPaid += (AdValue adValue) =>
        {
            Debug.Log(String.Format("Interstitial ad paid {0} {1}.",
                adValue.Value,
                adValue.CurrencyCode));
        };
        // Raised when an impression is recorded for an ad.
        interstitialAd.OnAdImpressionRecorded += () =>
        {
            Debug.Log("Interstitial ad recorded an impression.");
        };
        // Raised when a click is recorded for an ad.
        interstitialAd.OnAdClicked += () =>
        {
            Debug.Log("Interstitial ad was clicked.");
        };
        // Raised when an ad opened full screen content.
        interstitialAd.OnAdFullScreenContentOpened += () =>
        {
            DestroyAd();
            Debug.Log("Interstitial ad full screen content opened.");
        };
        // Raised when the ad closed full screen content.
        interstitialAd.OnAdFullScreenContentClosed += () =>
        {
            if (InsterAdsShowCompletedEvent != null) InsterAdsShowCompletedEvent();
            LoadIntersAd();
            //LoadBannerAd(bannerPos);
            Debug.Log("Interstitial ad full screen content closed.");
        };
        // Raised when the ad failed to open full screen content.
        interstitialAd.OnAdFullScreenContentFailed += (AdError error) =>
        {
            if (InsterAdsShowCompletedEvent != null) InsterAdsShowCompletedEvent();
            LoadIntersAd();
            Debug.LogError("Interstitial ad failed to open full screen content " +
                           "with error : " + error);
        };
    }

    // BANNER

    public void LoadBannerAd(AdsManager.BannerPos pos)
    {
        // create an instance of a banner view first.
        if (adBannerIds.Count == 0) return;
        bannerAdsIndex = adBannerIds.Count - 1;
        string adsID = adBannerIds[bannerAdsIndex];
        bannerPos = pos;
        CreateBannerView(adsID);


    }

    public void CreateBannerView(string _adUnitId)
    {
        // If we already have a banner, destroy the old one.
        if (_bannerView != null)
        {
            DestroyAd();
        }

        // Create a 320x50 banner at top of the screen
        if (bannerPos == AdsManager.BannerPos.Top)
            _bannerView = new BannerView(_adUnitId, AdSize.Banner, AdPosition.Top);
        else
            _bannerView = new BannerView(_adUnitId, AdSize.Banner, AdPosition.Bottom);
        // create our request used to load the ad.
        ListenToAdEvents();
        var adRequest = new AdRequest();
        // 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>
    private void ListenToAdEvents()
    {
        // Raised when an ad is loaded into the banner view.
        _bannerView.OnBannerAdLoaded += () =>
        {
            _bannerView.Show();
            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) =>
        {
            if (bannerAdsIndex == 0) return;
            bannerAdsIndex--;
            bannerAdsIndex = adBannerIds.Count - 1;
            string adsID = adBannerIds[bannerAdsIndex];
            CreateBannerView(adsID);
            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 += () =>
        {
            LoadBannerAd(bannerPos);
            Debug.Log("Banner view full screen content closed.");
        };
    }

    /// <summary>
    /// Destroys the banner view.
    /// </summary>
    public void DestroyAd()
    {
        if (_bannerView != null)
        {
            Debug.Log("Destroying banner view.");
            _bannerView.Destroy();
            _bannerView = null;
        }
    }
}

GOOGLE CONSENT UNITY INTEGRATED

using UnityEngine;
using System;
using GoogleMobileAds.Ump.Api;
using GoogleMobileAds.Ump.Common;
using GoogleMobileAds.Api;
public class ConsentManager : MonoBehaviour
{
    public static ConsentManager _this;
    private ConsentForm consentForm;
    [HideInInspector] public Action completedConsentEvent;
    void Awake()
    {
        _this = this;
        DontDestroyOnLoad(this);
    }
    void Start()
    {
        // Bước 1: Yêu cầu cập nhật thông tin chấp thuận
        ConsentRequestParameters request = new ConsentRequestParameters();

        // Check the current consent information status.
        ConsentInformation.Update(request, OnConsentInfoUpdated);
    }

    void OnConsentInfoUpdated(FormError consentError)
    {
        if (consentError != null)
        {
            // Handle the error.
            UnityEngine.Debug.LogError(consentError);
            return;
        }

        // If the error is null, the consent information state was updated.
        // You are now ready to check if a form is available.
        ConsentForm.LoadAndShowConsentFormIfRequired((FormError formError) =>
        {
            if (formError != null)
            {
                // Consent gathering failed.
                UnityEngine.Debug.LogError(consentError);
                return;
            }

            // Consent has been gathered.
            if (ConsentInformation.CanRequestAds())
            {
                completedConsentEvent += AdsAdmob._this.OnCompletedConsentEvent;
                InitializeAdMobSDK();
            }
        });
    }

    private void InitializeAdMobSDK()
    {
        // Bước 2: Khởi động AdMob SDK sau khi nhận được chấp thuận
        MobileAds.Initialize(initStatus =>
        {
            if (completedConsentEvent != null) completedConsentEvent();
            //Debug.Log("Admob SDK has started at consentManager");
        });
    }
}