using System; using UnityEngine; #if UNITY_IOS && !UNITY_EDITOR using GoogleMobileAds.Api; using GoogleMobileAds.Ump.Api; using System.Runtime.InteropServices; using System.Threading; #endif namespace HexaCrazy.Ads { public sealed class AdMobRewardedAds : RewardedAds { public static RewardedAds Shared() { if (instance != null) return instance; var host = new GameObject("AdMob Rewarded Ads"); DontDestroyOnLoad(host); instance = host.AddComponent(); return instance; } static AdMobRewardedAds instance; #if UNITY_IOS && !UNITY_EDITOR const string LiveUnit = "ca-app-pub-8449397879714583/5746003775"; const string TestUnit = "ca-app-pub-3940256099942544/1712485313"; [DllImport("__Internal")] static extern int HexaCrazyUseTestAds(); string unitId; RewardedAd loaded; SynchronizationContext main; bool checkingConsent, initializing, initialized, loading, privacyFormOpen; float retryDelay = 2; double loadedAt; public override bool Supported => true; public override bool NeedsPrivacyOptions => ConsentInformation.PrivacyOptionsRequirementStatus == PrivacyOptionsRequirementStatus.Required; void Start() { unitId = Debug.isDebugBuild || HexaCrazyUseTestAds() != 0 ? TestUnit : LiveUnit; Debug.Log($"[AdMob] Rewarded unit ({(unitId == TestUnit ? "test" : "live")}): {unitId}"); main = SynchronizationContext.Current; UpdateConsent(); } void OnMain(Action action) => main.Post(_ => { if (this != null) action(); }, null); void UpdateConsent() { if (checkingConsent || privacyFormOpen || initializing) return; CancelInvoke(nameof(UpdateConsent)); checkingConsent = true; Status = RewardedAdStatus.Preparing; ConsentInformation.Update(new ConsentRequestParameters(), error => OnMain(() => { if (error != null) { AfterConsent(error); return; } ConsentForm.LoadAndShowConsentFormIfRequired(formError => OnMain(() => AfterConsent(formError))); })); } void AfterConsent(FormError error) { checkingConsent = false; if (error != null) Debug.LogWarning("[AdMob] Consent: " + error.Message); if (!ConsentInformation.CanRequestAds()) { InvalidateLoaded(); Status = RewardedAdStatus.PrivacyUnavailable; if (error != null) Invoke(nameof(UpdateConsent), 60); return; } if (initialized) { if (loaded != null) Status = RewardedAdStatus.Ready; else Load(); return; } if (initializing) return; initializing = true; MobileAds.Initialize(status => OnMain(() => { initializing = false; initialized = status != null; if (initialized) Load(); else { Debug.LogWarning("[AdMob] Initialization returned no status."); Status = RewardedAdStatus.LoadFailed; Invoke(nameof(UpdateConsent), 30); } })); } public override void ShowPrivacyOptions() { if (privacyFormOpen || IsShowing || !NeedsPrivacyOptions) return; privacyFormOpen = true; Status = RewardedAdStatus.Preparing; InvalidateLoaded(); ConsentForm.ShowPrivacyOptionsForm(error => OnMain(() => { privacyFormOpen = false; AfterConsent(error); })); } int generation; public override void Retry() { if (checkingConsent || privacyFormOpen || initializing || loading || IsShowing) return; if (!initialized || !ConsentInformation.CanRequestAds()) UpdateConsent(); else Load(); } void InvalidateLoaded() { generation++; loaded?.Destroy(); loaded = null; } void Load() { CancelInvoke(nameof(Load)); if (!initialized || loading || loaded != null || IsShowing || privacyFormOpen || !ConsentInformation.CanRequestAds()) return; loading = true; Status = RewardedAdStatus.Loading; int request = generation; RewardedAd.Load(unitId, new AdRequest(), (ad, error) => OnMain(() => { loading = false; if (request != generation || !ConsentInformation.CanRequestAds()) { ad?.Destroy(); if (!privacyFormOpen && !ConsentInformation.CanRequestAds()) Status = RewardedAdStatus.PrivacyUnavailable; Load(); return; } if (error != null || ad == null) { ad?.Destroy(); Status = ClassifyLoadError(error); Debug.LogWarning($"[AdMob] Rewarded load ({(unitId == TestUnit ? "test" : "live")}) failed: " + $"{error?.GetDomain()} {error?.GetCode()} {error?.GetMessage()}; retry in {retryDelay}s."); Invoke(nameof(Load), retryDelay); retryDelay = Mathf.Min(60, retryDelay * 2); return; } loaded = ad; Status = RewardedAdStatus.Ready; loadedAt = Time.realtimeSinceStartupAsDouble; retryDelay = 2; })); } static RewardedAdStatus ClassifyLoadError(AdError error) { // The same numeric code can mean different things in different domains. for (int depth = 0; error != null && depth < 5; depth++, error = error.GetCause()) { string domain = error.GetDomain(); int code = error.GetCode(); if (domain == "com.google.admob") { if (code == 1) return RewardedAdStatus.NoFill; if (code == 2 || code == 5) return RewardedAdStatus.NetworkError; } if (domain == "NSURLErrorDomain" && (code == -1001 || code == -1003 || code == -1004 || code == -1005 || code == -1009)) return RewardedAdStatus.NetworkError; } return RewardedAdStatus.LoadFailed; } protected override bool Present(Action earn, Action close) { if (!initialized || privacyFormOpen || !ConsentInformation.CanRequestAds()) return false; if (loaded == null) return false; if (!loaded.CanShowAd() || Time.realtimeSinceStartupAsDouble - loadedAt >= 3600) { InvalidateLoaded(); Status = RewardedAdStatus.Loading; Invoke(nameof(Load), 0); return false; } var ad = loaded; loaded = null; bool ended = false; void End() { if (ended) return; ended = true; ad.Destroy(); try { close(); } finally { Load(); } } ad.OnAdFullScreenContentClosed += () => OnMain(End); ad.OnAdFullScreenContentFailed += error => OnMain(() => { Debug.LogWarning($"[AdMob] Rewarded show failed: {error.GetDomain()} {error.GetCode()} {error.GetMessage()}"); End(); }); try { ad.Show(reward => OnMain(earn)); } catch (Exception exception) { Debug.LogException(exception); End(); } return true; } #else public override bool Supported => false; protected override bool Present(Action earn, Action close) => false; #endif } }