Untitled

mail@pastecode.io avatar
unknown
csharp
a year ago
22 kB
2
Indexable
Never
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GoogleMobileAds.Api;
using GoogleMobileAds.Common;
using System;
using Firebase.Analytics;
using UnityEngine.UI;
//using GoogleMobileAdsMediationTestSuite.Api;

public class AdmobManager : MonoBehaviour
{
    private BannerView bannerView;
    private InterstitialAd interstitial;
    private InterstitialAd interstitial2;
    private RewardedAd rewardedAd;

    int bannerStep = 0;
    int interStep = 0;
    int rewardStep = 0;

    int delayUnitBannerSeconds = 0;
    int delaySetBannerSeconds = 20;
    int delayUnitInterSeconds = 1;
    int delaySetInterSeconds = 20;
    int delayUnitRewardSeconds = 1;
    int delaySetRewardSeconds = 20;

    Action<bool> rewardCallback = null;

    public string bannerId = "ca-app-pub-3902469414991170/1689088945";
    public string rewardIDSingle = "ca-app-pub-3902469414991170/7782317670";
    public string bannerIdDefault = "ca-app-pub-3902469414991170/1689088945";

    public string[] interstitialId = { "ca-app-pub-3902469414991170/1474388339","ca-app-pub-3902469414991170/7465081618","ca-app-pub-3902469414991170/4647346580","ca-app-pub-3902469414991170/4072631510","ca-app-pub-3902469414991170/2376406462","ca-app-pub-3902469414991170/3306344758","ca-app-pub-3902469414991170/4427854732","ca-app-pub-3902469414991170/8165461052" };
    public string[] interstitialIdDefault = { "ca-app-pub-3902469414991170/1474388339","ca-app-pub-3902469414991170/7465081618","ca-app-pub-3902469414991170/4647346580","ca-app-pub-3902469414991170/4072631510","ca-app-pub-3902469414991170/2376406462","ca-app-pub-3902469414991170/3306344758","ca-app-pub-3902469414991170/4427854732","ca-app-pub-3902469414991170/8165461052" };

    public string[] rewardId = { "ca-app-pub-3902469414991170/2540057990","ca-app-pub-3902469414991170/8339179587","ca-app-pub-3902469414991170/1773771234","ca-app-pub-3902469414991170/4016791197","ca-app-pub-3902469414991170/1422610966","ca-app-pub-3902469414991170/4978712596","ca-app-pub-3902469414991170/8726385919","ca-app-pub-3902469414991170/7782317670" };
    public string[] rewardIdDefault = { "ca-app-pub-3902469414991170/2540057990","ca-app-pub-3902469414991170/8339179587","ca-app-pub-3902469414991170/1773771234","ca-app-pub-3902469414991170/4016791197","ca-app-pub-3902469414991170/1422610966","ca-app-pub-3902469414991170/4978712596","ca-app-pub-3902469414991170/8726385919","ca-app-pub-3902469414991170/7782317670" };
    public string appOpenID = "ca-app-pub-3902469414991170/8903827658";


    public string appId = "ca-app-pub-3902469414991170~2915089440";


    bool adsInited;
    public static AdmobManager Instance { get; private set; }
    private void Awake()
    {
        Application.targetFrameRate = 60;
        Instance = this;
        GameObject.DontDestroyOnLoad(gameObject);
        #if !UNITY_EDITOR
                Debug.unityLogger.logEnabled = false;
        #endif
        StartCoroutine(MakeSureAds());
    }
    IEnumerator MakeSureAds()
    {
        yield return new WaitForSeconds(5);
        UpdateIDAds(bannerId, interstitialId, rewardId);
    }
    public void UpdateIDAds(string bannerID, string[] _interstitialId, string[] rewardID)
    {
        //get delay time for ad calls from remote config     
        if (GameRemote.Instance.dataRemote.delayUnitInter > -1)
            delayUnitInterSeconds = GameRemote.Instance.dataRemote.delayUnitInter;
        
        if (GameRemote.Instance.dataRemote.delaySetInter > -1)
                delaySetInterSeconds = GameRemote.Instance.dataRemote.delaySetInter;

        if (GameRemote.Instance.dataRemote.delayUnitReward >-1)
            delayUnitRewardSeconds = GameRemote.Instance.dataRemote.delayUnitReward;

        if (GameRemote.Instance.dataRemote.delaySetReward > -1)
            delaySetRewardSeconds = GameRemote.Instance.dataRemote.delaySetReward;

        if (!adsInited)
        {
            Debug.Log("Init Ads");
            adsInited = true;
            bannerId = bannerID;
            interstitialId = _interstitialId;
            rewardId = rewardID;
            InitAds();
        }
    }
    private void InitAds()
    {
        MobileAds.Initialize(initStatus =>
        {
            RequestInterstitial();
            RequestReward();
            //ShowAdaptiveBanner();
            //Debug.Log("Done initializing ads");
        });
    }
    public static bool IsRemoveAds
    {
        set { PlayerPrefs.SetInt("IsRemoveAds", value == true ? 1 : 0); }
        get { return PlayerPrefs.GetInt("IsRemoveAds", 0) == 1; }
    }

    public int PlayedCount
    {
        get { return PlayerPrefs.GetInt("PlayedCount", 0); }
        set { PlayerPrefs.SetInt("PlayedCount", value); }
    }
    public int AdCount
    {
        get { return PlayerPrefs.GetInt("AdCount", 0); }
        set { PlayerPrefs.SetInt("AdCount", value); }
    }
    public int AdCount2
    {
        get { return PlayerPrefs.GetInt("AdCount2", 0); }
        set { PlayerPrefs.SetInt("AdCount2", value); }
    }
    void ShowBannerEditor(bool show)
    {
    }

    bool bannerShowing = false;
    public void ShowAdaptiveBanner()
    {
        //if (bannerShowing)
            //return;

        if (this.bannerView != null)
        {
            this.bannerView.Destroy();
        }

        //make sure bannerId is not null 
        if (bannerId == null || bannerId.Length <1)
            bannerId = bannerIdDefault;

        AdSize adaptiveSize =
                AdSize.GetPortraitAnchoredAdaptiveBannerAdSizeWithWidth(AdSize.FullWidth);

        this.bannerView = new BannerView(bannerId, adaptiveSize, AdPosition.Bottom);

        // Register for ad events.
        this.bannerView.OnBannerAdLoaded += this.HandleAdLoaded;
        this.bannerView.OnBannerAdLoadFailed += this.HandleAdFailedToLoad;
        this.bannerView.OnAdFullScreenContentOpened += this.HandleAdOpened;
        this.bannerView.OnAdFullScreenContentClosed += this.HandleAdClosed;
        this.bannerView.OnAdPaid += this.HandleAdPaidEventBanner;
        // this.bannerView.OnAdLeavingApplication += this.HandleAdLeftApplication;

        AdRequest adRequest = new AdRequest.Builder()
            .Build();

        // Load a banner ad.
        this.bannerView.LoadAd(adRequest);
    }
    #region Banner callback handlers

    public void HandleAdLoaded()
    {
        MobileAdsEventExecutor.ExecuteInUpdate(() =>
        {
            bannerShowing = true;
            Debug.Log("Initialization complete.");
        });
    }

    public void HandleAdFailedToLoad(LoadAdError args)
    {
        MobileAdsEventExecutor.ExecuteInUpdate(() =>
        {
            bannerShowing = false;
        });
    }

    public void HandleAdOpened()
    {
        MobileAdsEventExecutor.ExecuteInUpdate(() =>
        {
            bannerShowing = true;
            MonoBehaviour.print("HandleAdOpened event received");
        });
    }

    public void HandleAdClosed()
    {
        MobileAdsEventExecutor.ExecuteInUpdate(() =>
        {
            bannerShowing = false;
            MonoBehaviour.print("HandleAdClosed event received");
        });
    }

    public void HandleAdLeftApplication(object sender, EventArgs args)
    {
        MobileAdsEventExecutor.ExecuteInUpdate(() =>
        {
            MonoBehaviour.print("HandleAdLeftApplication event received");
        });
    }
    public void HandleAdPaidEventBanner(AdValue args)
    {
        MobileAdsEventExecutor.ExecuteInUpdate(() =>
        {
            AdValue adValue = args;
            Firebase.Analytics.Parameter[] LTVParameters = {
            new Firebase.Analytics.Parameter("valuemicros", adValue.Value),
            new Firebase.Analytics.Parameter("value", adValue.Value/1000000f),
            new Firebase.Analytics.Parameter("currency", adValue.CurrencyCode)
            /*
            ,
            new Firebase.Analytics.Parameter("precision", (int)adValue.Precision),
            new Firebase.Analytics.Parameter("adunitid", bannerId),
            new Firebase.Analytics.Parameter("network", this.bannerView.GetResponseInfo().GetMediationAdapterClassName())
            */
        };

            Firebase.Analytics.FirebaseAnalytics.LogEvent("Ad_Impression_Revenue", LTVParameters);
            Firebase.Analytics.FirebaseAnalytics.LogEvent("Ad_Rev_3D", LTVParameters);
            Firebase.Analytics.FirebaseAnalytics.LogEvent("Ad_Rev_7D", LTVParameters);
            Firebase.Analytics.FirebaseAnalytics.LogEvent("Ad_Rev_14D", LTVParameters);
            Firebase.Analytics.FirebaseAnalytics.LogEvent("Ad_Rev_AllTime", LTVParameters);
        });
    }
    
    public void HideBanner()
    {
        if (bannerView != null)
            bannerView.Hide();
        ShowBannerEditor(false);
    }

    #endregion

    
    #region Inter
    private void RequestInterstitial()
    {
        int interIndex = 0;
        if (interstitial != null)
        {
            interstitial.Destroy();
            interstitial = null;
        }

        //make sure interstitialId array is not null
        if (interstitialId == null || interstitialId.Length<1)
            interstitialId = interstitialIdDefault;

        interIndex = Mathf.Clamp(interStep, 0 ,interstitialId.Length-1);
        if (interIndex < 0)
            interIndex = 0;

        //this.interstitial.OnAdLoaded += HandleOnAdLoaded;
        //this.interstitial.OnAdFailedToLoad += HandleOnAdFailedToLoad;    
        //this.interstitial.OnAdFailedToShow += HandleOnAdFailedShow;
        //this.interstitial.OnAdLeavingApplication += HandleOnAdLeavingApplication;

        // Create an empty ad request.
        AdRequest request = new AdRequest.Builder().Build();

        // Load the interstitial with the request.
        InterstitialAd.Load(interstitialId[interIndex], request,
        (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.GetMessage());
                HandleOnAdFailedToLoad();
                return;
            }

            Debug.Log("Interstitial ad loaded with response : " + ad.GetResponseInfo());
            interStep = 0;
            interstitial = ad;
            this.interstitial.OnAdFullScreenContentOpened += HandleOnAdOpened;
            // Called when the ad is closed.
            this.interstitial.OnAdFullScreenContentClosed += HandleOnAdClosed;
            // Called when the ad is paid.
            this.interstitial.OnAdPaid += HandleAdPaidEventInter;
        }
        );
    }
    
    Action onInterFinish;
    Action onInterFinish2;
    public void ShowInter(Action action)
    {
        onInterFinish = action;
        if (IsInterReady())
        {
            CheckEvent2();
            this.interstitial.Show();
            interStep = 0;
            RequestInterstitial();
        }
        else
        {
            RequestInterstitial();
            onInterFinish?.Invoke();
        }
    }

    public bool IsInterReady()
    {
        if (interstitial == null) 
            return false;
        if (!interstitial.CanShowAd() || IsRemoveAds)
        {
            return false;
        }
        else
        {
            if(GameController.Instance.CurrentLevel == GameRemote.Instance.startInter+1)
            {
                return true;
            }
            if (GameRemote.Instance.skipInter == 0)
            {
                return true;
            }
            else if (GameRemote.Instance.skipInter == 1)
            {
                if (GameController.Instance.CurrentLevel > GameRemote.Instance.startInter
                      && (GameController.Instance.CurrentLevel - (GameRemote.Instance.startInter+1)) % 2 == 0)
                {
                    return true;
                }
            }
            else
            {
                if (GameController.Instance.CurrentLevel > GameRemote.Instance.startInter
                      && (GameController.Instance.CurrentLevel - (GameRemote.Instance.startInter + 1)) % 3 == 0)
                {
                    return true;
                }
            }
        }
        return false;
    }
  
    int retryAttempt1;


    public void HandleOnAdFailedToLoad()
    {
        MobileAdsEventExecutor.ExecuteInUpdate(() =>
        {
            if (interStep < interstitialId.Length - 1)
            {
                interStep++;
                Invoke("RequestInterstitial", delayUnitInterSeconds);
            }
            else
            {
                interStep = 0;
                Invoke("RequestInterstitial", delaySetInterSeconds);
            }
        });
    }

    public void HandleOnAdOpened()
    {
        MobileAdsEventExecutor.ExecuteInUpdate(() =>
        {
            interStep = 0;
            CheckEvent();
            //MonoBehaviour.print("HandleAdOpened event received");
        });
    }

    public void HandleOnAdClosed()
    {
        MobileAdsEventExecutor.ExecuteInUpdate(() =>
        {
            interStep = 0;
            StartCoroutine(PlayCallBackInter1());
            //MonoBehaviour.print("HandleAdClosed event received");
        });
    }
    public void HandleAdPaidEventInter(AdValue args)
    {
        MobileAdsEventExecutor.ExecuteInUpdate(() =>
        {
            AdValue adValue = args;
            /*
            int interIndex = 0; 
            //make sure interstitialId is not null 
            if (interstitialId == null || interstitialId.Length<1)
                interstitialId = interstitialIdDefault;

            if (interStep < 0)
                interStep = 0;

            interIndex = Mathf.Clamp(interStep, 0, interstitialId.Length-1);

            if (interstitialId.Length<1)   //check IndexOutOfBound
                return; 

            */

            Firebase.Analytics.Parameter[] LTVParameters = {
            new Firebase.Analytics.Parameter("valuemicros", adValue.Value),
            new Firebase.Analytics.Parameter("value", adValue.Value/1000000f),
            new Firebase.Analytics.Parameter("currency", adValue.CurrencyCode)
            /*
            ,
            new Firebase.Analytics.Parameter("precision", (int)adValue.Precision),
            new Firebase.Analytics.Parameter("adunitid",interstitialId[interIndex]),
            new Firebase.Analytics.Parameter("network",
            this.interstitial.GetResponseInfo().GetMediationAdapterClassName())
            */
        };
            Firebase.Analytics.FirebaseAnalytics.LogEvent("Ad_Impression_Revenue", LTVParameters);
            Firebase.Analytics.FirebaseAnalytics.LogEvent("Ad_Rev_3D", LTVParameters);
            Firebase.Analytics.FirebaseAnalytics.LogEvent("Ad_Rev_7D", LTVParameters);
            Firebase.Analytics.FirebaseAnalytics.LogEvent("Ad_Rev_14D", LTVParameters);
            Firebase.Analytics.FirebaseAnalytics.LogEvent("Ad_Rev_AllTime", LTVParameters);
        });
    }
    
    IEnumerator PlayCallBackInter1()
    {
        yield return new WaitForSecondsRealtime(.4f);
        onInterFinish?.Invoke();
    }
    #endregion

    #region Reward
    private void RequestReward()
    {
        if (rewardedAd != null)
        {
            rewardedAd.Destroy();
            rewardedAd = null;
        }

        //make sure rewardId is not null 
        if (rewardId.Length < 1)
            rewardId = rewardIdDefault; 


        if (rewardId == null || rewardId.Length < 1)
            return;

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

        // send the request to load the ad.
        RewardedAd.Load(rewardId[Mathf.Clamp(rewardStep, 0, rewardId.Length - 1)], adRequest,
            (RewardedAd ad, LoadAdError error) =>
            {
                 // if error is not null, the load request failed.
                if (error != null || ad == null)
                {
                    HandleRewardedAdFailedToLoad();
                    return;               
                }
  
                rewardStep = 0;
                rewardedAd = ad;

                this.rewardedAd.OnAdFullScreenContentOpened += HandleRewardedAdOpening;
                this.rewardedAd.OnAdFullScreenContentFailed += HandleRewardedAdFailedToShow;
                this.rewardedAd.OnAdFullScreenContentClosed += HandleRewardedAdClosed;
                this.rewardedAd.OnAdPaid += HandleAdPaidEventRewarded;
            });
    }
    public bool IsRewardReady()
    {
        if (rewardedAd == null) return false;
        return rewardedAd.CanShowAd();

    }
    public void ShowReward(Action<bool> callback)
    {
        rewardCallback = callback;

        if (isEditor())
        {
            rewardCallback(true);
        }
        else
        {
            if (IsRewardReady())
            {
                rewardedAd.Show((Reward reward) =>
                {
                    callback(true);
                });
                CheckEvent2();
                rewardStep = 0;
                RequestReward();
            }
            else
            {
                if (rewardStep < rewardId.Length - 1)
                {
                    rewardStep++;
                    Invoke("RequestReward", delayUnitRewardSeconds);
                }
                else
                {
                    rewardStep = 0;
                    Invoke("RequestReward", delaySetRewardSeconds);
                }
            }
        }
    }
  

    public void HandleRewardedAdFailedToLoad()
    {
        if (rewardStep < rewardId.Length - 1)
        {
            rewardStep++;
            Invoke("RequestReward", delayUnitRewardSeconds);
        }
        else
        {
            rewardStep = 0;
            Invoke("RequestReward", delaySetRewardSeconds);
        }
    }

    public void HandleRewardedAdOpening()
    {
        CheckEvent();
        MonoBehaviour.print("HandleRewardedAdOpening event received");
    }

    public void HandleRewardedAdFailedToShow(AdError args)
    {
        rewardCallback(false);
        if (rewardStep < rewardId.Length - 1)
        {
            rewardStep++;
            Invoke("RequestReward", delayUnitRewardSeconds);
        }
        else
        {
            rewardStep = 0;
            Invoke("RequestReward", delaySetRewardSeconds);
        }
    }

    public void HandleRewardedAdClosed()
    {
        rewardStep = 0;
        MonoBehaviour.print("HandleRewardedAdClosed event received");
    }
    public void HandleAdPaidEventRewarded(AdValue args)
    {
        AdValue adValue = args;
        /*
        int rewardIndex = 0;
        //make sure rewardId is not null 
        if (rewardId.Length<1)
            rewardId = rewardIdDefault;

        rewardIndex = Mathf.Clamp(rewardStep, 0, rewardId.Length-1);

        if (rewardIndex < 0)
            rewardIndex = 0;

        if (rewardId == null || rewardId.Length < 1)
            return;

        */
        Firebase.Analytics.Parameter[] LTVParameters = {
            new Firebase.Analytics.Parameter("valuemicros", adValue.Value),
            new Firebase.Analytics.Parameter("value", adValue.Value/1000000f),
            new Firebase.Analytics.Parameter("currency", adValue.CurrencyCode)
            /*
            ,
            new Firebase.Analytics.Parameter("precision", (int)adValue.Precision),
            new Firebase.Analytics.Parameter("adunitid",rewardId[rewardIndex]),
            new Firebase.Analytics.Parameter("network", this.rewardedAd.GetResponseInfo().GetMediationAdapterClassName())
            */

        };
        Firebase.Analytics.FirebaseAnalytics.LogEvent("Ad_Impression_Revenue", LTVParameters);
        Firebase.Analytics.FirebaseAnalytics.LogEvent("Ad_Rev_3D", LTVParameters);
        Firebase.Analytics.FirebaseAnalytics.LogEvent("Ad_Rev_7D", LTVParameters);
        Firebase.Analytics.FirebaseAnalytics.LogEvent("Ad_Rev_14D", LTVParameters);
        Firebase.Analytics.FirebaseAnalytics.LogEvent("Ad_Rev_AllTime", LTVParameters);
    }
   

    void CheckEvent()
    {
        AdCount++;
        if (AdCount == 5 || AdCount == 8 || AdCount == 10 || AdCount == 12 || AdCount == 15 || AdCount == 18 || AdCount == 29 || AdCount == 25 || AdCount == 30)
        {
            string data = "view_" + AdCount + "_ads";
            Firebase.Analytics.FirebaseAnalytics.LogEvent(data);
        }
    }
    void CheckEvent2()
    {
        AdCount2++;
        if (AdCount2 == 5 || AdCount2 == 8 || AdCount2 == 10 || AdCount2 == 12 || AdCount2 == 15 || AdCount2 == 18 || AdCount2 == 29 || AdCount2 == 25 || AdCount2 == 30)
        {
            string data = "view_" + AdCount2;
            Firebase.Analytics.FirebaseAnalytics.LogEvent(data);
        }
    }
    #endregion

    bool isEditor()
    {
    #if UNITY_EDITOR
            return true;
    #elif UNITY_ANDROID || UNITY_IOS
            return false;
    #endif
    }
}