I saw this easy implementation to integrate Unity Ads in my project (Sorry, didn’t find an option to insert code):
private IEnumerator PlayAd()
{
while (!Advertisement.isInitialized || !Advertisement.IsReady())
{
yield return new WaitForSeconds(0.5f);
}
Advertisement.Show();
}
Will this cause an endless loop when the user has no connection to the internet? I mean, without internet connection, the ad can never be ready, thus I am stuck inside the while loop. If I am wrong, please explain why.
Thanks
Yes, you have the potential for an endless loop here. I’d recommend utilizing the OnDisable and OnDestroy MonoBehaviour methods to StopAllCoroutines running on the script.
You can also implement a timeout, exiting the loop if unable to show after a length of time.
using UnityEngine;
using System.Collections;
using UnityEngine.Advertisements;
public class UnityAdsExample : MonoBehaviour
{
public string zoneId; // Specify a placement ID, or leave empty to use the default placement.
public float initTimeout = 15f; // Time in seconds to allow for initialization.
public float showTimeout = 15f; // Time in seconds to allow ads to be ready.
private float _yieldTime = 0.5f; // Time in seconds to wait between attempts.
private IEnumerator ShowAdWhenReady ()
{
float startTime = Time.timeSinceLevelLoad;
if (!Advertisement.isSupported) yield break;
while (!Advertisement.isInitialized)
{
if (Time.timeSinceLevelLoad - startTime > initTimeout)
{
Debug.LogWarning("Unity Ads failed to initialize in a timely manner.");
yield break;
}
yield return new WaitForSeconds(_yieldTime);
}
Debug.Log("Unity Ads has finished initializing. Waiting for ads to be ready...");
startTime = Time.timeSinceLevelLoad;
while (!Advertisement.IsReady(zoneId))
{
if (Time.timeSinceLevelLoad - startTime > showTimeout)
{
Debug.LogWarning("Unity Ads failed to be ready in a timely manner.");
yield break;
}
yield return new WaitForSeconds(_yieldTime);
}
Debug.Log("Ads are available and ready.");
Advertisement.Show(zoneId);
}
}
1 Like
Thanks, looks great! I didn’t know anything about the yield keyword before, and therefore simple integration code was a bit irritating (as I said I wasn’t sure if this produces an endless loop or yield has some special behavior on that).