Unity AdMob 5.4 Singleton Script

Unity AdMob 5.4 Singeleton Script

Unity AdMob 5.4 Singeleton Script

AdMob ile reklamlarınızı kolay bir şekilde yönetebilmeniz için singeleton olarak yazılmış reklam yönetim scripti kodları.

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

// ReSharper disable once CheckNamespace
namespace UrhobA.Google.AdManager5x4
{
    public class AdManager : MonoBehaviour
    {
        private static AdManager _adManager;
        
        private InterstitialAd _interstitialAd;
        private BannerView _bannerView;
        private RewardedAd _rewardedAd;
        
        [SerializeField] private string
            bannerAdID,
            interstitialAdID,
            rewardedAdID;

        [SerializeField] private bool testMode, childMode;
        [SerializeField] private string testDeviceID;
        [SerializeField] private AdPosition bannerPosition;
        
        private IEnumerator _interstitialShowCoroutine, _rewardedAdShowCoroutine;

        private float
            _interstitialRequestTimeOutTime,
            _rewardedVideoRequestTimeOutTime;


        private float
            _autoBannerAdRequestTime = float.PositiveInfinity,
            _autoInterstitialAdRequestTime = float.PositiveInfinity,
            _autoRewardedAdRequestTime = float.PositiveInfinity;

        public delegate void RewardedAdGift(Reward gift);
        private RewardedAdGift _giftDelegate;
        
        private void Awake()
        {
            if (_adManager == null)
            {
                _adManager = this;
                DontDestroyOnLoad(this);

                #region Trim ID
                bannerAdID = bannerAdID.Trim();
                interstitialAdID = interstitialAdID.Trim();
                rewardedAdID = rewardedAdID.Trim();

                testDeviceID = testDeviceID.Trim();
                #endregion
                
                MobileAds.Initialize(adStatus => {});

                #region ADS Configuration

                var adConfiguration = new RequestConfiguration.Builder();
                
                if (testMode && !string.IsNullOrEmpty(testDeviceID))
                    adConfiguration.SetTestDeviceIds(new List() {testDeviceID});

                if (childMode)
                    adConfiguration.SetTagForChildDirectedTreatment(TagForChildDirectedTreatment.True);
            
                MobileAds.SetRequestConfiguration(adConfiguration.build());

                #endregion
                
                BannerAdLoad();
                InterstitialAdLoad();
                RewardedAdLoad();

            }else if(this != _adManager) Destroy(this);
        }

        private void Update()
        {
            var time = Time.realtimeSinceStartup;
        
            if (time >= _autoBannerAdRequestTime)
            {
                _autoBannerAdRequestTime = float.PositiveInfinity;
                BannerAdLoad();
            }

            if (time >= _autoInterstitialAdRequestTime)
            {
                _autoInterstitialAdRequestTime = float.PositiveInfinity;
                InterstitialAdLoad();
            }

            if (time >= _autoRewardedAdRequestTime)
            {
                _autoRewardedAdRequestTime = float.PositiveInfinity;
                RewardedAdLoad();
            }
        }

        #region Banner Ad
        private void BannerAdLoad()
        {
            if(!testMode && string.IsNullOrEmpty(bannerAdID))
                return;
            
            _bannerView?.Destroy();
            
            if (testMode && (string.IsNullOrEmpty(bannerAdID) || string.IsNullOrEmpty(testDeviceID)))
            {
#if UNITY_ANDROID
                _bannerView = new BannerView("ca-app-pub-3940256099942544/6300978111", AdSize.SmartBanner, bannerPosition);
#else
                _bannerView = new BannerView("ca-app-pub-3940256099942544/2934735716", AdSize.SmartBanner, bannerPosition);
#endif
            }
            else
            {
                _bannerView = new BannerView(bannerAdID, AdSize.SmartBanner, bannerPosition);
            }
            
            _bannerView.OnAdFailedToLoad += BannerViewLoadFailed;
            _bannerView.LoadAd(CreateAddRequest());
            _bannerView.Hide();
        }
        private void BannerViewLoadFailed(object sender, AdFailedToLoadEventArgs adFailedToLoadEventArgs)
        {
            Debug.Log(adFailedToLoadEventArgs.Message);

            if (_bannerView == null) return;
            
            _bannerView.Destroy();
            _bannerView = null;
        }

        public static void OnGetBannerAd() => GetBannerAd();
        private static void GetBannerAd()
        {
            if(_adManager == null) return;
            _adManager.BannerAdLoad();
        }

        public static void OnShowBannerAd() => ShowBannerAd();
        private static void ShowBannerAd()
        {
            if(_adManager == null)
                return;

            if (_adManager._bannerView == null)
            {
                _adManager.BannerAdLoad();
                if(_adManager._bannerView == null)
                    return;
            }
        
            _adManager._bannerView.Show();
        }

        public static void OnHideBannerAd() => HideBannerAd();
        private static void HideBannerAd()
        {
            if(_adManager == null)
                return;

            _adManager._bannerView?.Hide();
        }
        #endregion

        #region Interstitial Ad

        private void InterstitialAdLoad()
        {
            if(!testMode && string.IsNullOrEmpty(interstitialAdID))
                return;
        
            if(_interstitialAd != null && _interstitialAd.IsLoaded())
                return;
        
            _interstitialAd?.Destroy();

            if (testMode && (string.IsNullOrEmpty(testDeviceID) || string.IsNullOrEmpty(interstitialAdID)))
            {
#if UNITY_ANDROID
                _interstitialAd = new InterstitialAd("ca-app-pub-3940256099942544/1033173712");
#else
                _interstitialAd = new InterstitialAd("ca-app-pub-3940256099942544/4411468910");
#endif
            }
            else
                _interstitialAd = new InterstitialAd(interstitialAdID);
            
            _interstitialAd.OnAdClosed += InterstitialDelegate;
            _interstitialAd.OnAdFailedToLoad += InterstitialAdLoadFailed;
            _interstitialAd.LoadAd(CreateAddRequest());

            _interstitialRequestTimeOutTime = Time.realtimeSinceStartup + 10f;
        }
        private void InterstitialAdLoadFailed(object sender, AdFailedToLoadEventArgs adFailedToLoadEventArgs)
        {
            Debug.Log(adFailedToLoadEventArgs.Message);
            _autoInterstitialAdRequestTime = Time.realtimeSinceStartup + 30f;

            if (_interstitialAd == null) return;
            _interstitialAd.Destroy();
            _interstitialAd = null;
        }
        private void InterstitialDelegate(object sender, EventArgs eventArgs)
        {
            InterstitialAdLoad();
        }

        public static bool OnCheckInterstitialAd() => CheckInterstitialAd();
        private static bool CheckInterstitialAd()
        {
            if (_adManager == null)
                return false;

            return _adManager._interstitialAd != null && _adManager._interstitialAd.IsLoaded();
        }

        public static void OnGetInterstitialAd() => GetInterstitialAd();
        private static void GetInterstitialAd()
        {
            if (_adManager == null)
                return;
            _adManager.InterstitialAdLoad();
        }

        public static void OnShowInterstitialAd() => ShowInterstitialAd();
        private static void ShowInterstitialAd()
        {
            if(_adManager == null)
                return;

            if (_adManager._interstitialAd == null)
            {
                _adManager.InterstitialAdLoad();
                if(_adManager._interstitialAd == null)
                    return;
            }

            if (_adManager._interstitialShowCoroutine != null)
            {
                _adManager.StopCoroutine(_adManager._interstitialShowCoroutine);
                _adManager._interstitialShowCoroutine = null;
            }

            if (_adManager._interstitialAd.IsLoaded())
                _adManager._interstitialAd.Show();
            else
            {
                if(Time.realtimeSinceStartup >= _adManager._interstitialRequestTimeOutTime)
                    _adManager.InterstitialAdLoad();

                _adManager._interstitialShowCoroutine = _adManager.InterstitialShowCoroutine();
                _adManager.StartCoroutine(_adManager._interstitialShowCoroutine);
            }
        
        }
        private IEnumerator InterstitialShowCoroutine()
        {
            var requestTimeOutNow = Time.realtimeSinceStartup + 2.5f;
        
            while (!_interstitialAd.IsLoaded())
            {
                if(Time.realtimeSinceStartup > requestTimeOutNow)
                    yield break;
            
                yield return null;

                if (_interstitialAd == null)
                    yield break;
            }
        
            _interstitialAd.Show();
        }
        #endregion

        #region Rewarded Ad
        private void RewardedAdLoad()
        {
            if(!testMode && string.IsNullOrEmpty(rewardedAdID))
                return;
        
            if(_rewardedAd != null && _rewardedAd.IsLoaded())
                return;

            if (testMode && (string.IsNullOrEmpty(testDeviceID) || string.IsNullOrEmpty(rewardedAdID)))
            {
#if UNITY_ANDROID
                _rewardedAd = new RewardedAd("ca-app-pub-3940256099942544/5224354917");
#else
                _rewardedAd = new RewardedAd("ca-app-pub-3940256099942544/1712485313");
#endif
            }
            else
                _rewardedAd = new RewardedAd(rewardedAdID);

            _rewardedAd.OnAdClosed += RewardedAdDelegate;
            _rewardedAd.OnAdFailedToLoad += RewardedAdLoadFailed;
            _rewardedAd.OnUserEarnedReward += RewardedAdSendGift;
            _rewardedAd.LoadAd(CreateAddRequest());

            _rewardedVideoRequestTimeOutTime = Time.realtimeSinceStartup + 30f;
        }
        private void RewardedAdLoadFailed(object sender,AdErrorEventArgs adFailedToLoadEventArgs)
        {
            Debug.Log(adFailedToLoadEventArgs.Message);
            _autoRewardedAdRequestTime = Time.realtimeSinceStartup + 30f;

            if (_adManager != null)
            {
                _rewardedAd = null;
            }
        }
        private void RewardedAdDelegate(object sender, EventArgs eventArgs)
        {
            RewardedAdLoad();
        }
        private void RewardedAdSendGift(object sender, Reward gift)
        {
            if (_giftDelegate == null) return;
            _giftDelegate(gift);
            _giftDelegate = null;
        }

        public static bool OnCheckRewardedAd() => CheckRewardedAd();
        private static bool CheckRewardedAd()
        {
            if (_adManager == null)
                return false;

            return _adManager._rewardedAd != null && _adManager._rewardedAd.IsLoaded();
        }

        public static void OnGetRewardedAd() => GetRewardedAd();
        private static void GetRewardedAd()
        {
            if(_adManager == null)
                return;
            
            _adManager.RewardedAdLoad();
        }

        public static void OnShowRewardedAd(RewardedAdGift rewardedAdGift) => ShowRewardedAd(rewardedAdGift);
        private static void ShowRewardedAd(RewardedAdGift rewardedAdGift)
        {
            if (_adManager == null)
                return;

            if (_adManager._rewardedAd == null)
            {
                _adManager.RewardedAdLoad();
                if(_adManager._rewardedAd == null)
                    return;
            }

            if (_adManager._rewardedAdShowCoroutine != null)
            {
                _adManager.StopCoroutine(_adManager._rewardedAdShowCoroutine);
                _adManager._rewardedAdShowCoroutine = null;
            }

            _adManager._giftDelegate = rewardedAdGift;
        
            if(_adManager._rewardedAd.IsLoaded())
                _adManager._rewardedAd.Show();
            else
            {
                if(Time.realtimeSinceStartup >= _adManager._rewardedVideoRequestTimeOutTime)
                    _adManager.RewardedAdLoad();

                _adManager._rewardedAdShowCoroutine = _adManager.RewardedAdShowCoroutine();
                _adManager.StartCoroutine(_adManager._rewardedAdShowCoroutine);
            }

        }
        private IEnumerator RewardedAdShowCoroutine()
        {
            var requestTimeOutNow = Time.realtimeSinceStartup + 10f;
            while (!_rewardedAd.IsLoaded())
            {
                if(Time.realtimeSinceStartup > requestTimeOutNow)
                    yield break;

                yield return null;
            
                if(_rewardedAd == null)
                    yield break;
            }
            _rewardedAd.Show();
        }
        #endregion
        private static AdRequest CreateAddRequest()
        {
            return new AdRequest.Builder().Build();
        }
    }   
}

Scripti projenize dahil ettikten sonra inspector penceresinden gerekli düzenlemeleri yaptıktan sonra;

using UrhobA.Google.AdManager5x5; 

i scriptinize ekleyip, kullanmak istediğiniz reklam komutunu

 AdManager.ShowBannerAd();

AdManager.ShowInterstitialAd();

AdManager.ShowRewardedAd();

diyerek kullanabilirsiniz.

Projenin GitHub sayfasına gitmek için aşağıdaki bağlantıyı kullanabilirsiniz.

UrhobA -> GitHub