AdMobRewardedAds.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. using System;
  2. using UnityEngine;
  3. #if UNITY_IOS && !UNITY_EDITOR
  4. using GoogleMobileAds.Api;
  5. using GoogleMobileAds.Ump.Api;
  6. using System.Runtime.InteropServices;
  7. using System.Threading;
  8. #endif
  9. namespace HexaCrazy.Ads
  10. {
  11. public sealed class AdMobRewardedAds : RewardedAds
  12. {
  13. public static RewardedAds Shared()
  14. {
  15. if (instance != null) return instance;
  16. var host = new GameObject("AdMob Rewarded Ads");
  17. DontDestroyOnLoad(host);
  18. instance = host.AddComponent<AdMobRewardedAds>();
  19. return instance;
  20. }
  21. static AdMobRewardedAds instance;
  22. #if UNITY_IOS && !UNITY_EDITOR
  23. const string LiveUnit = "ca-app-pub-8449397879714583/5746003775";
  24. const string TestUnit = "ca-app-pub-3940256099942544/1712485313";
  25. [DllImport("__Internal")]
  26. static extern int HexaCrazyUseTestAds();
  27. string unitId;
  28. RewardedAd loaded;
  29. SynchronizationContext main;
  30. bool checkingConsent, initializing, initialized, loading, privacyFormOpen;
  31. float retryDelay = 2;
  32. double loadedAt;
  33. public override bool Supported => true;
  34. public override bool NeedsPrivacyOptions =>
  35. ConsentInformation.PrivacyOptionsRequirementStatus == PrivacyOptionsRequirementStatus.Required;
  36. void Start()
  37. {
  38. unitId = Debug.isDebugBuild || HexaCrazyUseTestAds() != 0 ? TestUnit : LiveUnit;
  39. Debug.Log($"[AdMob] Rewarded unit ({(unitId == TestUnit ? "test" : "live")}): {unitId}");
  40. main = SynchronizationContext.Current;
  41. UpdateConsent();
  42. }
  43. void OnMain(Action action) => main.Post(_ => { if (this != null) action(); }, null);
  44. void UpdateConsent()
  45. {
  46. if (checkingConsent || privacyFormOpen || initializing) return;
  47. CancelInvoke(nameof(UpdateConsent));
  48. checkingConsent = true;
  49. Status = RewardedAdStatus.Preparing;
  50. ConsentInformation.Update(new ConsentRequestParameters(), error => OnMain(() =>
  51. {
  52. if (error != null) { AfterConsent(error); return; }
  53. ConsentForm.LoadAndShowConsentFormIfRequired(formError => OnMain(() => AfterConsent(formError)));
  54. }));
  55. }
  56. void AfterConsent(FormError error)
  57. {
  58. checkingConsent = false;
  59. if (error != null) Debug.LogWarning("[AdMob] Consent: " + error.Message);
  60. if (!ConsentInformation.CanRequestAds())
  61. {
  62. InvalidateLoaded();
  63. Status = RewardedAdStatus.PrivacyUnavailable;
  64. if (error != null) Invoke(nameof(UpdateConsent), 60);
  65. return;
  66. }
  67. if (initialized)
  68. {
  69. if (loaded != null) Status = RewardedAdStatus.Ready;
  70. else Load();
  71. return;
  72. }
  73. if (initializing) return;
  74. initializing = true;
  75. MobileAds.Initialize(status => OnMain(() =>
  76. {
  77. initializing = false;
  78. initialized = status != null;
  79. if (initialized) Load();
  80. else
  81. {
  82. Debug.LogWarning("[AdMob] Initialization returned no status.");
  83. Status = RewardedAdStatus.LoadFailed;
  84. Invoke(nameof(UpdateConsent), 30);
  85. }
  86. }));
  87. }
  88. public override void ShowPrivacyOptions()
  89. {
  90. if (privacyFormOpen || IsShowing || !NeedsPrivacyOptions) return;
  91. privacyFormOpen = true;
  92. Status = RewardedAdStatus.Preparing;
  93. InvalidateLoaded();
  94. ConsentForm.ShowPrivacyOptionsForm(error => OnMain(() =>
  95. {
  96. privacyFormOpen = false;
  97. AfterConsent(error);
  98. }));
  99. }
  100. int generation;
  101. public override void Retry()
  102. {
  103. if (checkingConsent || privacyFormOpen || initializing || loading || IsShowing) return;
  104. if (!initialized || !ConsentInformation.CanRequestAds()) UpdateConsent();
  105. else Load();
  106. }
  107. void InvalidateLoaded()
  108. {
  109. generation++;
  110. loaded?.Destroy();
  111. loaded = null;
  112. }
  113. void Load()
  114. {
  115. CancelInvoke(nameof(Load));
  116. if (!initialized || loading || loaded != null || IsShowing || privacyFormOpen || !ConsentInformation.CanRequestAds()) return;
  117. loading = true;
  118. Status = RewardedAdStatus.Loading;
  119. int request = generation;
  120. RewardedAd.Load(unitId, new AdRequest(), (ad, error) => OnMain(() =>
  121. {
  122. loading = false;
  123. if (request != generation || !ConsentInformation.CanRequestAds())
  124. {
  125. ad?.Destroy();
  126. if (!privacyFormOpen && !ConsentInformation.CanRequestAds()) Status = RewardedAdStatus.PrivacyUnavailable;
  127. Load();
  128. return;
  129. }
  130. if (error != null || ad == null)
  131. {
  132. ad?.Destroy();
  133. Status = ClassifyLoadError(error);
  134. Debug.LogWarning($"[AdMob] Rewarded load ({(unitId == TestUnit ? "test" : "live")}) failed: " +
  135. $"{error?.GetDomain()} {error?.GetCode()} {error?.GetMessage()}; retry in {retryDelay}s.");
  136. Invoke(nameof(Load), retryDelay);
  137. retryDelay = Mathf.Min(60, retryDelay * 2);
  138. return;
  139. }
  140. loaded = ad;
  141. Status = RewardedAdStatus.Ready;
  142. loadedAt = Time.realtimeSinceStartupAsDouble;
  143. retryDelay = 2;
  144. }));
  145. }
  146. static RewardedAdStatus ClassifyLoadError(AdError error)
  147. {
  148. // The same numeric code can mean different things in different domains.
  149. for (int depth = 0; error != null && depth < 5; depth++, error = error.GetCause())
  150. {
  151. string domain = error.GetDomain();
  152. int code = error.GetCode();
  153. if (domain == "com.google.admob")
  154. {
  155. if (code == 1) return RewardedAdStatus.NoFill;
  156. if (code == 2 || code == 5) return RewardedAdStatus.NetworkError;
  157. }
  158. if (domain == "NSURLErrorDomain" && (code == -1001 || code == -1003 || code == -1004 || code == -1005 || code == -1009))
  159. return RewardedAdStatus.NetworkError;
  160. }
  161. return RewardedAdStatus.LoadFailed;
  162. }
  163. protected override bool Present(Action earn, Action close)
  164. {
  165. if (!initialized || privacyFormOpen || !ConsentInformation.CanRequestAds()) return false;
  166. if (loaded == null) return false;
  167. if (!loaded.CanShowAd() || Time.realtimeSinceStartupAsDouble - loadedAt >= 3600)
  168. {
  169. InvalidateLoaded();
  170. Status = RewardedAdStatus.Loading;
  171. Invoke(nameof(Load), 0);
  172. return false;
  173. }
  174. var ad = loaded;
  175. loaded = null;
  176. bool ended = false;
  177. void End()
  178. {
  179. if (ended) return;
  180. ended = true;
  181. ad.Destroy();
  182. try { close(); } finally { Load(); }
  183. }
  184. ad.OnAdFullScreenContentClosed += () => OnMain(End);
  185. ad.OnAdFullScreenContentFailed += error => OnMain(() =>
  186. {
  187. Debug.LogWarning($"[AdMob] Rewarded show failed: {error.GetDomain()} {error.GetCode()} {error.GetMessage()}");
  188. End();
  189. });
  190. try { ad.Show(reward => OnMain(earn)); }
  191. catch (Exception exception) { Debug.LogException(exception); End(); }
  192. return true;
  193. }
  194. #else
  195. public override bool Supported => false;
  196. protected override bool Present(Action earn, Action close) => false;
  197. #endif
  198. }
  199. }