using System; using GoogleMobileAds.Api; using GoogleMobileAds.Common; using UnityEngine; namespace TowerDevil { public sealed partial class TowerGame { #if UNITY_IOS && TOWERDEVIL_LIVE_ADS && !UNITY_EDITOR && !DEVELOPMENT_BUILD const string RewardedUnit = "ca-app-pub-8449397879714583/6772795358"; #elif UNITY_ANDROID const string RewardedUnit = "ca-app-pub-3940256099942544/5224354917"; #else const string RewardedUnit = "ca-app-pub-3940256099942544/1712485313"; #endif RewardedAd rewardedAd; bool adsInitialized, preparingAd, watchingAd; double adLoadedAt; void PrepareRewardedAd() { #if UNITY_EDITOR || UNITY_IOS || UNITY_ANDROID if (preparingAd || watchingAd) return; preparingAd = true; if (adsInitialized) { LoadRewardedAd(); return; } MobileAds.Initialize(status => MobileAdsEventExecutor.ExecuteInUpdate(() => { if (!this) return; adsInitialized = status != null; if (adsInitialized) LoadRewardedAd(); else preparingAd = false; })); #endif } void LoadRewardedAd() { rewardedAd?.Destroy(); rewardedAd = null; RewardedAd.Load(RewardedUnit, new AdRequest(), (ad, error) => MobileAdsEventExecutor.ExecuteInUpdate(() => { preparingAd = false; if (!this || error != null || ad == null) { ad?.Destroy(); if (error != null) Debug.LogWarning("Rewarded ad load failed: " + error); return; } rewardedAd = ad; adLoadedAt = Time.realtimeSinceStartupAsDouble; })); } void Ad(Action reward) { if (watchingAd) return; var ad = rewardedAd; if (ad == null || !ad.CanShowAd() || Time.realtimeSinceStartupAsDouble - adLoadedAt >= 3600) { PrepareRewardedAd(); Toast("AD UNAVAILABLE · TRY AGAIN SHORTLY"); return; } watchingAd = true; OpenCompactMenu("REWARDED VIDEO", closable: false); bool earned = false; void Finish(bool failed) { if (!this || rewardedAd != ad || !watchingAd) return; watchingAd = false; rewardedAd = null; ad.Destroy(); CloseSheet(); PrepareRewardedAd(); if (earned && !failed) reward(); else Toast(failed ? "AD UNAVAILABLE · TRY AGAIN" : "AD CLOSED · NO REWARD"); } ad.OnAdFullScreenContentClosed += () => MobileAdsEventExecutor.ExecuteInUpdate(() => Finish(false)); ad.OnAdFullScreenContentFailed += error => MobileAdsEventExecutor.ExecuteInUpdate(() => { Debug.LogWarning("Rewarded ad presentation failed: " + error); Finish(true); }); ad.Show(_ => MobileAdsEventExecutor.ExecuteInUpdate(() => earned = true)); } } }