1

In my project, the banner opens after the scene is reloaded, everything seems to be in order in the editor.

Everything works fine in the editor, I checked it, but it’s only worth building the project on Android, it doesn’t work there normally. It will appear only after the scene is reloaded, and then not immediately with a delay of 2-3 seconds.

My code:

using UnityEngine;
using System.Collections;
using UnityEngine.Advertisements;

public class BannerAd : MonoBehaviour
{
[SerializeField] BannerPosition _bannerPosition;

[SerializeField] private string _androidAdUnitId = "Banner_Android";
[SerializeField] private string _iOSAdUnitId = "Banner_iOS";

private string _adUnitId;

private void Awake()
{
    _adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
        ? _iOSAdUnitId
        : _androidAdUnitId;
}

private void Start()
{
    Advertisement.Banner.SetPosition(_bannerPosition);
    LoadBanner();
}

private IEnumerator LoadAdBanner()
{
    yield return new WaitForSeconds(1f);
    LoadBanner();
}

public void LoadBanner()
{
    BannerLoadOptions options = new BannerLoadOptions
    {
        loadCallback = OnBannerLoaded,
        errorCallback = OnBannerError
    };

    Advertisement.Banner.Load(_adUnitId, options);
}

private void OnBannerLoaded()
{
    Debug.Log("Banner loaded");
    ShowBannerAd();
}

private void OnBannerError(string message)
{
    Debug.Log($"Banner Error: {message}");
}

public void ShowBannerAd()
{
    BannerOptions options = new BannerOptions
    {
        clickCallback = OnBannerClicked,
        hideCallback = OnBannerHidden,
        showCallback = OnBannerShown
    };

    Advertisement.Banner.Show(_adUnitId, options);  
}

public void HideBannerAd()
{
    Advertisement.Banner.Hide();
}

private void OnBannerClicked() { }
private void OnBannerShown() { }
private void OnBannerHidden() { }
}
Young Frog
  • 11
  • 3

1 Answers1

1

It might be the ad is still not initialized when you call LoadBanner so it doesn't work at first. The best is to call LoadBanner when Initialization is complete. Set _testMode to true or false based on your need.

public class BannerAd  : MonoBehaviour, IUnityAdsInitializationListener
{
    [SerializeField] bool _testMode = true;
    
    private string _adUnitId;
       
     void Awake()
        {
            InitializeAds();
        }
     
        public void InitializeAds()
        {
            _adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
                ? _iOSGameId
                : _androidGameId;
            Advertisement.Initialize(_adUnitId, _testMode, this);
        }
     
        public void OnInitializationComplete()
        {
            LoadBanner();
        }
    
         //rest of the code
    
    }
}
     
Milad Qasemi
  • 3,011
  • 3
  • 13
  • 17