Space Ad Mobile 9.5.1
Space Ad Mobile makes ads easy to add into your mobile game: one unified workflow for LevelPlay, AdMob, Yandex.Ads across banners, interstitials and rewarded.
Loading...
Searching...
No Matches
AdUnit.cs
1using System;
2using System.Collections;
3using System.Collections.Generic;
4using UnityEngine;
5
7{
16 public abstract class AdUnit<TAd> : AdUnitHandlerBase
17 {
22 public TAd AdObject { get; protected set; }
23
24 [SerializeField]
25 [Tooltip("Ad unit ID for Android.")]
26 private string androidId;
27 [SerializeField]
28 [Tooltip("Ad unit ID for iOS.")]
29 private string iOSId;
30
31 [SerializeField]
32 [Tooltip("Behavior options for displaying and showing ads.")]
33 private AdBehaviour adBehaviour = new();
34
35 [SerializeField]
36 [Tooltip("Options for enabling Unity SendMessage methods.")]
37 private MessageOptions messageOptions = new();
38
40 public override AdBehaviour AdBehaviour => adBehaviour;
42 public override MessageOptions MessageOptions => messageOptions;
43
46 {
48 set => SpaceAdMobileBase.Options = value;
49 }
50
57
59 public virtual LogOptions LogOptions => Options.LogOptions;
60
62 protected SpaceAdLogger Logger { get; private set; }
63
68 protected virtual bool ShouldUnloadOnLoad => true;
69
74 protected virtual bool ShouldUnloadOnShow => false;
75
80 protected abstract bool SdkInitialized { get; }
81
85 protected Type SystemAdType { get; private set; }
89 protected string SystemAdTypeName { get; private set; }
90
96 private static readonly Dictionary<string, TAd> cachedAdUnits = new();
97
98 private bool wasShown;
99 private bool wasAwakened;
100
102 protected override void Awake()
103 {
104 SystemAdType = typeof(TAd);
106 Logger = InitLogger();
107
108 Options ??= !Application.isEditor
109 ? throw new UnityException($"The {nameof(SpaceAdMobileBase)} script must be added to the first scene.")
110 : new();
111
112#if !DEBUG
113 var debug = false;
114#else
115 var debug = Options.AdMode != AdMode.Development;
116#endif
117 if (debug && RuntimePlatformGuard.IsRuntimePlatformSupported &&
118 string.IsNullOrEmpty(androidId) && string.IsNullOrEmpty(iOSId))
119 {
120 throw new UnityException("At least one ID is required, but both Android and iOS IDs are empty!");
121 }
122
123 UnityAwake();
124 wasAwakened = true;
125 }
126
128 protected override void OnEnable()
129 {
130 if (!RuntimePlatformGuard.IsRuntimePlatformSupported) return;
131
132 if (AdBehaviour.AutoLoadOnEnable)
133 {
134 if (!SdkInitialized && Options.AwaitSDKInitialization)
135 {
136 IEnumerator WaitForReady()
137 {
138 yield return new WaitWhile(() => !SdkInitialized);
139 Load();
140 }
141
142 StartCoroutine(WaitForReady());
143 }
144 else
145 {
146 Load();
147 }
148 }
149
151 }
152
154 protected override void OnDestroy()
155 {
157 base.OnDestroy();
158 //Unity OnApplicationQuit
159 if (Options == null)
160 return;
161
162 //If cache is active and ad has not been shown, it can be shown later.
163 //Last verification is for Test IDs that contain the same IDs.
164 if (Options.CacheAds && CanShowAd() && !cachedAdUnits.ContainsKey(GetId()))
165 {
166 cachedAdUnits.Add(GetId(), AdObject);
168 }
169 else
170 {
171 Unload();
172 }
173
175 }
176
178 protected override void OnApplicationQuit()
179 {
180 Unload();
181 cachedAdUnits.Clear();
183 }
184
189 public override bool Load() => TryPrepareLoad() && LoadInternal();
190
200 protected bool TryPrepareLoad()
201 {
202 EnsureScriptReady();
203
204 if (!RuntimePlatformGuard.EnsureSupported()) return false;
205
206 if (Options.CacheAds && cachedAdUnits.ContainsKey(GetId()))
207 {
208 Logger.Log(LogOptions.AdCachedLoadLogText);
209 AdObject = cachedAdUnits[GetId()];
211 OnAdLoaded();
212 cachedAdUnits.Remove(GetId());
213 return false;
214 }
215
217 Unload();
218
219 if (!SdkInitialized && Options.AwaitSDKInitialization)
220 {
221 Logger.LogWarning(LogOptions.SdkNotInitializedLogText);
222 return false;
223 }
224
225 if (InternetConnection.CheckInternetConnection()) return true;
226
227 Logger.LogWarning(LogOptions.NoInternetLogText);
229 return false;
230 }
231
233 private protected override void OnAdLoadedInternal() => wasShown = false;
234
236 public override bool CanShowAd() =>
237 RuntimePlatformGuard.IsRuntimePlatformSupported &&
238 AdObject != null &&
239 (!ShouldUnloadOnShow || !wasShown);
240
246 public override void Show()
247 {
248 EnsureScriptReady();
249
250 if (!RuntimePlatformGuard.EnsureSupported()) return;
251
252 if (AdObject != null && CanShowAd())
253 {
254 if (ShouldUnloadOnShow) wasShown = true;
255
256 Logger.Log(LogOptions.AdShowingLogText);
258 try
259 {
260 ShowInternal();
261 }
262 catch
263 {
265 throw;
266 }
267 }
268 else
269 {
270 if (AdBehaviour.LoadOnDemand)
271 {
272 Logger.Log(LogOptions.AdUnavailableLogText);
273 Load();
274 }
275 else
276 {
277 Logger.LogWarning(LogOptions.AdUnavailableLogText);
278 }
279 }
280 }
281
285 public override void Unload()
286 {
288
289 if (AdObject == null)
290 {
291 wasShown = false;
292 return;
293 }
294
295 OnUnload();
297 AdObject = default;
298 wasShown = false;
299 }
300
301 private void EnsureScriptReady()
302 {
303 if (!wasAwakened)
304 throw new InvalidOperationException("The script is not ready yet. Wait until Awake has completed before calling this method.");
305
306 if (SystemAdType == null)
307 throw new InvalidOperationException("The component is not initialized yet. Enable it before calling this method.");
308 }
309
311 protected abstract bool LoadInternal();
312
317 protected abstract SpaceAdLogger InitLogger();
318
323 protected internal string GetRealId() =>
324 RuntimePlatformGuard.GetAdUnitId(androidId, iOSId);
325
332 protected string GetId() =>
333 RuntimePlatformGuard.GetAdUnitId(
334 Options.AdMode == AdMode.Development ? TestAndroidId : androidId,
335 Options.AdMode == AdMode.Development ? TestIOSId : iOSId);
336 }
337}
Options and behaviors that control how ads are handled, loaded, and displayed.
override bool Load()
Loads the ad.
Definition AdUnit.cs:189
bool SdkInitialized
Indicates if the necessary SDK has been properly initialized. This is critical for ensuring that ad o...
Definition AdUnit.cs:80
override void Unload()
Unloads the ad.
Definition AdUnit.cs:285
override void OnApplicationQuit()
Definition AdUnit.cs:178
string GetId()
Determines and returns the appropriate ad ID based on the current platform and ad mode....
Definition AdUnit.cs:332
override void OnAdLoadedInternal()
Definition AdUnit.cs:233
TAd AdObject
The ad object associated with this unit. This property allows for direct interaction with the specifi...
Definition AdUnit.cs:22
virtual bool ShouldUnloadOnLoad
Determines whether the ad object should be unloaded when loading a new ad instance....
Definition AdUnit.cs:68
override void OnDestroy()
Definition AdUnit.cs:154
override bool CanShowAd()
Verifies if the ad is ready to be shown.True if the ad can be shown, otherwise false.
Definition AdUnit.cs:236
virtual bool ShouldUnloadOnShow
Determines whether the ad object should be treated as unavailable after being shown....
Definition AdUnit.cs:74
virtual IInternetConnectionChecker InternetConnection
Definition AdUnit.cs:53
override void Show()
Shows the ad.
Definition AdUnit.cs:246
override void OnEnable()
Definition AdUnit.cs:128
Type SystemAdType
Stores the type of the system ad, facilitating reflection and type-specific operations.
Definition AdUnit.cs:85
override AdBehaviour AdBehaviour
Definition AdUnit.cs:40
override MessageOptions MessageOptions
Definition AdUnit.cs:42
virtual AdvertisingOptions Options
Definition AdUnit.cs:46
string SystemAdTypeName
A convenient string representation of the system ad type, used primarily for logging and debugging pu...
Definition AdUnit.cs:89
SpaceAdLogger InitLogger()
Initializes and returns a logger.
override void Awake()
Definition AdUnit.cs:102
bool TryPrepareLoad()
Performs shared loading preflight used by synchronous and asynchronous provider implementations....
Definition AdUnit.cs:200
virtual LogOptions LogOptions
Definition AdUnit.cs:59
virtual void OnInternetNotAvailable()
Raised when the Internet connection isn't available. Can be overridden to handle this scenario.
Definition AdUnitBase.cs:85
string TestAndroidId
Gets the Android test ad unit identifier for the active provider.
Definition AdUnitBase.cs:41
void ReleaseFullscreenAdAudio()
Releases the audio policy for the current fullscreen ad show.
string TestIOSId
Gets the iOS test ad unit identifier for the active provider.
Definition AdUnitBase.cs:62
void AcquireFullscreenAdAudioLease()
Replaces the current fullscreen audio lease with a new one.
void OnAttachToCache()
Method to be called when the object is attached to the cache. It needs to unsubscribe from events it ...
void OnLoadFromCache()
Method to be called when the object is loaded from the cache. It needs to subscribe to needed events.
virtual void UnityOnDestroy()
Unity OnDestroy.
virtual void OnUnload()
Called when an ad is unloaded. Can be overridden to perform clean-up or other logic when the ad is no...
virtual void UnityOnApplicationQuit()
Unity OnApplicationQuit.
virtual void UnityOnEnable()
Unity OnEnable.
void DestroyInternal()
Internal method for unloading an ad. Must be implemented to handle the specific unloading logic.
void ShowInternal()
Internal method for showing an ad. Must be implemented to handle the specific showing logic.
override void OnAdLoaded()
Raised when the AdObject is loaded.
Serves as a base handler for ad unit operations, abstracting common functionality for different types...
Defines general configuration options for ad display, testing, and SDK initialization.
Defines options for enabling message callbacks related to ad events. These options allow you to subsc...
static AdvertisingOptions Options
General configuration options for ad display, testing, and SDK initialization.
static IInternetConnectionChecker InternetConnection
Pluggable internet checker instance. Assign a custom implementation if needed; null assignments are i...
Base class of the main SpaceAd mobile advertising manager. It provides a framework for initializing a...
Contract for pluggable internet connectivity checkers. Implementations should return true when the ne...
AdMode
Enumerates options for ad testing types, affecting whether real or test ads are displayed.