Миграция с Unity Ads на медиацию Яндекса на Unity

Подключение Mobile Ads Unity плагина

Mobile Ads Unity — плагин для игровой платформы Unity3d, включающий поддержку Yandex Mobile Ads SDK.

Примечание

  1. Для работы SDK требуется Target API Level версии 31 и выше.
  2. Для загрузки любого вида рекламы необходима версия iOS 12.0 и выше.

Интеграция плагина

Примечание

yandex-ads-unity-plugin работает только в окружениях Android и iOS. Работа в редакторе Unity невозможна.

Lite-версия

  1. Скачайте каталог yandex-ads-unity-plugin и добавьте пакет yandex-mobileads-lite-2.7.0.unitypackage. Вместе с ним будет предложено установить Google resolver. Если в ваш проект уже добавлен Google resolver, уберите галочку.

    Выберите необходимый плагин Assets → Import Package → Custom Package и нажмите кнопку Import.

  2. С помощью Google resolver установите зависимости: включите auto-resolve или выберите в меню пункт Assets → External Dependency Manager → Android Resolver → Resolve.

  3. Чтобы проверить работу Mobile Ads Unity плагина, воспользуйтесь одним из демонстрационных скриптов в каталоге samples репозитория yandex-ads-unity-plugin. Скопируйте скрипт в каталог с проектом и добавьте как Component в основную камеру.

Понижение Target API Level

Чтобы понизить Target API Level до версии 30, добавьте в mainTemplate.gradle и launcherTemplate.gradle (если launcherTemplate используется в проекте) явное понижение версии:

configurations.all {
    resolutionStrategy {
        force 'androidx.core:core:1.6.0'
        force 'androidx.core:core-ktx:1.6.0'
    }
}

Однако рекомендуется обновление до Target API Level версии 31, так как у Google есть ограничения на выпуск обновлений для приложений с устаревшей версией Target API Level. Подробнее в статье.

Описание ошибок

Полноэкранная реклама Unity Ads не отображается, ошибка «Incorrect fullscreen view»

Во время запуска полноэкранной рекламы на iOS возможна ошибка «Incorrect fullscreen view». При возникновении этой проблемы проверьте, что в настройках Build Phases, секции Copy Bundle Resource добавлено значение YandexMobileAdsBundle.bundle. Если значение отсутствует, добавьте его.

Форматы рекламы

Чтобы заменить рекламу Unity Ads на медиацию Yandex Ads, внесите в свой код следующие изменения.

Interstitial

using UnityEngine;
using UnityEngine.Advertisements;

public class InterstitialAdExample : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
    [SerializeField] string _androidAdUnitId = "Interstitial_Android";
    [SerializeField] string _iOsAdUnitId = "Interstitial_iOS";
    string _adUnitId;

    void Awake()
    {
        // Get the Ad Unit ID for the current platform:
        _adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
            ? _iOsAdUnitId
            : _androidAdUnitId;
    }

    // Load content to the Ad Unit:
    public void LoadAd()
    {
        // IMPORTANT! Only load content AFTER initialization (in this example, initialization is handled in a different script).
        Debug.Log("Loading Ad: " + _adUnitId);
        Advertisement.Load(_adUnitId, this);
    }

    // Show the loaded content in the Ad Unit:
    public void ShowAd()
    {
        // Note that if the ad content wasn't previously loaded, this method will fail
        Debug.Log("Showing Ad: " + _adUnitId);
        Advertisement.Show(_adUnitId, this);
    }

    // Implement Load Listener and Show Listener interface methods:
    public void OnUnityAdsAdLoaded(string adUnitId)
    {
        // Optionally execute code if the Ad Unit successfully loads content.
    }

    public void OnUnityAdsFailedToLoad(string adUnitId, UnityAdsLoadError error, string message)
    {
        Debug.Log($"Error loading Ad Unit: {adUnitId} - {error.ToString()} - {message}");
        // Optionally execute code if the Ad Unit fails to load, such as attempting to try again.
    }

    public void OnUnityAdsShowFailure(string adUnitId, UnityAdsShowError error, string message)
    {
        Debug.Log($"Error showing Ad Unit {adUnitId}: {error.ToString()} - {message}");
        // Optionally execute code if the Ad Unit fails to show, such as loading another ad.
    }

    public void OnUnityAdsShowStart(string adUnitId) { }
    public void OnUnityAdsShowClick(string adUnitId) { }
    public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState) { }
}
using UnityEngine;
using YandexMobileAds;
using YandexMobileAds.Base;

public class InterstitialAdExample : MonoBehaviour
{
    //replace these Ids with your ad_unit_id from Yandex Partner Interface
        [SerializeField] string _androidAdUnitId = "demo-interstitial-yandex";
    [SerializeField] string _iOsAdUnitId = "demo-interstitial-yandex";
    string _adUnitId;
    private Interstitial interstitial;

    void Awake()
    {
        // Get the Ad Unit ID for the current platform:
        _adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
            ? _iOsAdUnitId
            : _androidAdUnitId;

        interstitial = new Interstitial(_adUnitId);

        //To track events that occur in interstitial ads, register a delegate for the appropriate EventHandler, as shown below:
        // Called when an ad request has successfully loaded.
        this.interstitial.OnInterstitialLoaded += this.HandleInterstitialLoaded;
        // Called when an ad request failed to load.
        this.interstitial.OnInterstitialFailedToLoad += this.HandleInterstitialFailedToLoad;
        // Called when user returned to application after click.
        this.interstitial.OnReturnedToApplication += this.HandleReturnedToApplication;
        // Called when user is about to leave application after tapping on an ad.
        this.interstitial.OnLeftApplication += this.HandleLeftApplication;
        // Called when user clicked on the ad.
        this.interstitial.OnAdClicked += this.HandleAdClicked;
        // Called when an ad is shown.
        this.interstitial.OnInterstitialShown += this.HandleInterstitialShown;
        // Called when the ad is closed.
        this.interstitial.OnInterstitialDismissed += this.HandleInterstitialDismissed;
        // Called when an impression was tracked
        this.interstitial.OnImpression += this.HandleImpression;
        // Called when an ad request failed to show.
        this.interstitial.OnInterstitialFailedToShow += this.HandleInterstitialFailedToShow;
    }

    // Load interstitial ad:
    public void LoadAd()
    {
        Debug.Log("Loading Ad: " + _adUnitId);

        AdRequest request = new AdRequest.Builder().Build();
        interstitial.LoadAd(request);
    }

    // Show the loaded interstitial ad:
    public void ShowAd()
    {
        Debug.Log("Showing Ad: " + _adUnitId);
        if (this.interstitial.IsLoaded())
        {
            interstitial.Show();
        }
        else
        {
            Debug.Log("Interstitial is not ready yet");
        }
    }

    void OnDestroy()
    {
        //Clean up the ad
        interstitial.Destroy();
    }

    public void HandleInterstitialLoaded(object sender, EventArgs args)
    {
        ShowAd();
        Debug.Log("HandleInterstitialLoaded event received");
    }

    public void HandleInterstitialFailedToLoad(object sender, AdFailureEventArgs args)
    {
        Debug.Log("HandleInterstitialFailedToLoad event received with message: {args.Message}");
    }

    public void HandleReturnedToApplication(object sender, EventArgs args)
    {
        Debug.Log("HandleReturnedToApplication event received");
    }

    public void HandleLeftApplication(object sender, EventArgs args)
    {
        Debug.Log("HandleLeftApplication event received");
    }

    public void HandleAdClicked(object sender, EventArgs args)
    {
        Debug.Log("HandleAdClicked event received");
    }

    public void HandleInterstitialShown(object sender, EventArgs args)
    {
        Debug.Log("HandleInterstitialShown event received");
    }

    public void HandleInterstitialDismissed(object sender, EventArgs args)
    {
        Debug.Log("HandleInterstitialDismissed event received");
    }

    public void HandleImpression(object sender, ImpressionData impressionData)
    {
        var data = impressionData == null ? "null" : impressionData.rawData;
        Debug.Log("HandleImpression event received with data: {data}");
    }

    public void HandleInterstitialFailedToShow(object sender, AdFailureEventArgs args)
    {
        Debug.Log("HandleInterstitialFailedToShow event received with message: {args.Message}");
    }
}

Banner

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Advertisements;

public class BannerAdExample : MonoBehaviour
{
    // For the purpose of this example, these buttons are for functionality testing:
    [SerializeField] Button _loadBannerButton;
    [SerializeField] Button _showBannerButton;
    [SerializeField] Button _hideBannerButton;

    [SerializeField] BannerPosition _bannerPosition = BannerPosition.BOTTOM_CENTER;

    [SerializeField] string _androidAdUnitId = "Banner_Android";
    [SerializeField] string _iOSAdUnitId = "Banner_iOS";
    string _adUnitId = null; // This will remain null for unsupported platforms.

    void Start()
    {
        // Get the Ad Unit ID for the current platform:
#if UNITY_IOS
        _adUnitId = _iOSAdUnitId;
#elif UNITY_ANDROID
        _adUnitId = _androidAdUnitId;
#endif

        // Disable the button until an ad is ready to show:
        _showBannerButton.interactable = false;
        _hideBannerButton.interactable = false;

        // Set the banner position:
        Advertisement.Banner.SetPosition(_bannerPosition);

        // Configure the Load Banner button to call the LoadBanner() method when clicked:
        _loadBannerButton.onClick.AddListener(LoadBanner);
        _loadBannerButton.interactable = true;
    }

    // Implement a method to call when the Load Banner button is clicked:
    public void LoadBanner()
    {
        // Set up options to notify the SDK of load events:
        BannerLoadOptions options = new BannerLoadOptions
        {
            loadCallback = OnBannerLoaded,
            errorCallback = OnBannerError
        };

        // Load the Ad Unit with banner content:
        Advertisement.Banner.Load(_adUnitId, options);
    }

    // Implement code to execute when the loadCallback event triggers:
    void OnBannerLoaded()
    {
        Debug.Log("Banner loaded");

        // Configure the Show Banner button to call the ShowBannerAd() method when clicked:
        _showBannerButton.onClick.AddListener(ShowBannerAd);
        // Configure the Hide Banner button to call the HideBannerAd() method when clicked:
        _hideBannerButton.onClick.AddListener(HideBannerAd);

        // Enable both buttons:
        _showBannerButton.interactable = true;
        _hideBannerButton.interactable = true;
    }

    // Implement code to execute when the load errorCallback event triggers:
    void OnBannerError(string message)
    {
        Debug.Log($"Banner Error: {message}");
        // Optionally execute additional code, such as attempting to load another ad.
    }

    // Implement a method to call when the Show Banner button is clicked:
    void ShowBannerAd()
    {
        // Set up options to notify the SDK of show events:
        BannerOptions options = new BannerOptions
        {
            clickCallback = OnBannerClicked,
            hideCallback = OnBannerHidden,
            showCallback = OnBannerShown
        };

        // Show the loaded Banner Ad Unit:
        Advertisement.Banner.Show(_adUnitId, options);
    }

    // Implement a method to call when the Hide Banner button is clicked:
    void HideBannerAd()
    {
        // Hide the banner:
        Advertisement.Banner.Hide();
    }

    void OnBannerClicked() { }
    void OnBannerShown() { }
    void OnBannerHidden() { }

    void OnDestroy()
    {
        // Clean up the listeners:
        _loadBannerButton.onClick.RemoveAllListeners();
        _showBannerButton.onClick.RemoveAllListeners();
        _hideBannerButton.onClick.RemoveAllListeners();
    }
}
using UnityEngine;
using UnityEngine.UI;
using YandexMobileAds;
using YandexMobileAds.Base;

public class BannerAdExample : MonoBehaviour
{
    // For the purpose of this example, these buttons are for functionality testing:
    [SerializeField] Button _loadBannerButton;

    [SerializeField] string _androidAdUnitId = "demo-banner-yandex";
    [SerializeField] string _iOSAdUnitId = "demo-banner-yandex";
    string _adUnitId = null;
    private Banner banner;

    void Start()
    {
        // Get the Ad Unit ID for the current platform:
#if UNITY_IOS
        _adUnitId = _iOSAdUnitId;
#elif UNITY_ANDROID
        _adUnitId = _androidAdUnitId;
#endif

        // Create a 320x50 banner and set position.
        this.banner = new Banner(adUnitId, AdSize.BANNER_320x50, AdPosition.TopCenter);

        //To track events that occur in banner, register a delegate for the appropriate EventHandler, as shown below:
        banner.OnAdLoaded += this.HandleAdLoaded;
        banner.OnAdFailedToLoad += this.HandleAdFailedToLoad;
        banner.OnReturnedToApplication += this.HandleReturnedToApplication;
        banner.OnLeftApplication += this.HandleLeftApplication;
        banner.OnAdClicked += this.HandleAdClicked;
        banner.OnImpression += this.HandleImpression;

        // Disable the button until an ad is ready to show:
        _showBannerButton.interactable = false;
        _hideBannerButton.interactable = false;

        // Configure the Load Banner button to call the LoadBanner() method when clicked:
        _loadBannerButton.onClick.AddListener(LoadBanner);
        _loadBannerButton.interactable = true;
    }

    // Implement a method to call when the Load Banner button is clicked:
    public void LoadBanner()
    {
        // Create an empty ad request.
        AdRequest request = new AdRequest.Builder().Build();
        // Load the banner with the request.
        banner.LoadAd(request);
    }

    // Implement code to execute when the loadCallback event triggers:
    void OnBannerLoaded()
    {
        Debug.Log("Banner loaded");

        // Configure the Show Banner button to call the ShowBannerAd() method when clicked:
        _showBannerButton.onClick.AddListener(ShowBannerAd);
        // Configure the Hide Banner button to call the HideBannerAd() method when clicked:
        _hideBannerButton.onClick.AddListener(HideBannerAd);

        // Enable both buttons:
        _showBannerButton.interactable = true;
        _hideBannerButton.interactable = true;
    }

    // Implement code to execute when the load errorCallback event triggers:
    void OnBannerError(string message)
    {
        Debug.Log($"Banner Error: {message}");
        // Optionally execute additional code, such as attempting to load another ad.
    }

    // Implement a method to call when the Show Banner button is clicked:
    void ShowBannerAd()
    {
        // Show the loaded Banner Ad Unit:
        banner.Show();
    }

    // Implement a method to call when the Hide Banner button is clicked:
    void HideBannerAd()
    {
        // Hide the banner:
        banner.Hide();
    }

    void OnDestroy()
    {
        //Clean up the ad
        banner.Destroy();
        // Clean up the listeners:
        _loadBannerButton.onClick.RemoveAllListeners();
        _showBannerButton.onClick.RemoveAllListeners();
        _hideBannerButton.onClick.RemoveAllListeners();
    }

    public void HandleAdLoaded(object sender, EventArgs args)
    {
        Debug.log("HandleAdLoaded event received");
        ShowBannerAd();
    }

    public void HandleAdFailedToLoad(object sender, AdFailureEventArgs args)
    {
        Debug.log("HandleAdFailedToLoad event received with message: {args.Message}");
    }

    public void HandleLeftApplication(object sender, EventArgs args)
    {
        Debug.log("HandleLeftApplication event received");
    }

    public void HandleReturnedToApplication(object sender, EventArgs args)
    {
        Debug.log("HandleReturnedToApplication event received");
    }

    public void HandleAdLeftApplication(object sender, EventArgs args)
    {
        Debug.log("HandleAdLeftApplication event received");
    }

    public void HandleAdClicked(object sender, EventArgs args)
    {
        Debug.log("HandleAdClicked event received");
    }

    public void HandleImpression(object sender, ImpressionData impressionData)
    {
        var data = impressionData == null ? "null" : impressionData.rawData;
        Debug.log("HandleImpression event received with data: {data}");
    }
}

Rewarded

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Advertisements;

public class RewardedAdsButton : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
    [SerializeField] Button _showAdButton;
    [SerializeField] string _androidAdUnitId = "Rewarded_Android";
    [SerializeField] string _iOSAdUnitId = "Rewarded_iOS";
    string _adUnitId = null; // This will remain null for unsupported platforms

    void Awake()
    {
        // Get the Ad Unit ID for the current platform:
#if UNITY_IOS
        _adUnitId = _iOSAdUnitId;
#elif UNITY_ANDROID
        _adUnitId = _androidAdUnitId;
#endif

        //Disable the button until the ad is ready to show:
        _showAdButton.interactable = false;
    }

    // Load content to the Ad Unit:
    public void LoadAd()
    {
        // IMPORTANT! Only load content AFTER initialization (in this example, initialization is handled in a different script).
        Debug.Log("Loading Ad: " + _adUnitId);
        Advertisement.Load(_adUnitId, this);
    }

    // If the ad successfully loads, add a listener to the button and enable it:
    public void OnUnityAdsAdLoaded(string adUnitId)
    {
        Debug.Log("Ad Loaded: " + adUnitId);

        if (adUnitId.Equals(_adUnitId))
        {
            // Configure the button to call the ShowAd() method when clicked:
            _showAdButton.onClick.AddListener(ShowAd);
            // Enable the button for users to click:
            _showAdButton.interactable = true;
        }
    }

    // Implement a method to execute when the user clicks the button:
    public void ShowAd()
    {
        // Disable the button:
        _showAdButton.interactable = false;
        // Then show the ad:
        Advertisement.Show(_adUnitId, this);
    }

    // Implement the Show Listener's OnUnityAdsShowComplete callback method to determine if the user gets a reward:
    public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState)
    {
        if (adUnitId.Equals(_adUnitId) && showCompletionState.Equals(UnityAdsShowCompletionState.COMPLETED))
        {
            Debug.Log("UnityAds Rewarded Ad Completed");
            // Grant a reward.

            // Load another ad:
            Advertisement.Load(_adUnitId, this);
        }
    }

    // Implement Load and Show Listener error callbacks:
    public void OnUnityAdsFailedToLoad(string adUnitId, UnityAdsLoadError error, string message)
    {
        Debug.Log($"Error loading Ad Unit {adUnitId}: {error.ToString()} - {message}");
        // Use the error details to determine whether to try to load another ad.
    }

    public void OnUnityAdsShowFailure(string adUnitId, UnityAdsShowError error, string message)
    {
        Debug.Log($"Error showing Ad Unit {adUnitId}: {error.ToString()} - {message}");
        // Use the error details to determine whether to try to load another ad.
    }

    public void OnUnityAdsShowStart(string adUnitId) { }
    public void OnUnityAdsShowClick(string adUnitId) { }

    void OnDestroy()
    {
        // Clean up the button listeners:
        _showAdButton.onClick.RemoveAllListeners();
    }
}
using UnityEngine;
using UnityEngine.UI;
using YandexMobileAds;
using YandexMobileAds.Base;

public class RewardedAdsButton : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
    [SerializeField] Button _showAdButton;
    [SerializeField] string _androidAdUnitId = "demo-rewarded-yandex";
    [SerializeField] string _iOSAdUnitId = "demo-rewarded-yandex";
    private RewardedAd rewardedAd;
    string _adUnitId = null; // This will remain null for unsupported platforms

    void Awake()
    {
#if UNITY_IOS
        _adUnitId = _iOSAdUnitId;
#elif UNITY_ANDROID
        _adUnitId = _androidAdUnitId;
#endif

        this.rewardedAd = new RewardedAd(_adUnitId);

       //To track events that occur in rewaarded ads, register a delegate for the appropriate EventHandler, as shown below:
        // Called when an ad request has successfully loaded.
        this.rewardedAd.OnRewardedAdLoaded += this.HandleRewardedAdLoaded;
        // Called when an ad request failed to load.
        this.rewardedAd.OnRewardedAdFailedToLoad += this.HandleRewardedAdFailedToLoad;
        // Called when user returned to application after click.
        this.rewardedAd.OnReturnedToApplication += this.HandleReturnedToApplication;
        // Called when user is about to leave application after tapping on an ad.
        this.rewardedAd.OnLeftApplication += this.HandleLeftApplication;
        // Called when user clicked on the ad.
        this.rewardedAd.OnAdClicked += this.HandleAdClicked;
        // Called when an ad is shown.
        this.rewardedAd.OnRewardedAdShown += this.HandleRewardedAdShown;
        // Called when the ad is closed.
        this.rewardedAd.OnRewardedAdDismissed += this.HandleRewardedAdDismissed;
        // Called when an impression was tracked
        this.rewardedAd.OnImpression += this.HandleImpression;
        // Called when the user should be rewarded for interacting with the ad.
        this.rewardedAd.OnRewarded += this.HandleRewarded;
        // Called when an ad request failed to show.
        this.rewardedAd.OnRewardedAdFailedToShow += this.HandleRewardedAdFailedToShow;

        //Disable the button until the ad is ready to show:
        _showAdButton.interactable = false;
    }

    // Load content to the Ad Unit:
    public void LoadAd()
    {
        Debug.Log("Loading Ad: " + _adUnitId);
        // Create an empty ad request.
        AdRequest request = new AdRequest.Builder().Build();
        // Load the rewarded with the request.
        this.rewardedAd.LoadAd(request);
    }

    // Implement a method to execute when the user clicks the button:
    public void ShowAd()
    {

        if (this.rewardedAd.IsLoaded())
        {
            // Disable the button:
            _showAdButton.interactable = false;
            rewardedAd.Show();
        }
        else
        {
            Debug.Log("Rewarded Ad is not ready yet");
        }
    }

    // If the ad successfully loads, add a listener to the button and enable it:
    public void HandleRewardedAdLoaded(object sender, EventArgs args)
    {
        // Configure the button to call the ShowAd() method when clicked:
        _showAdButton.onClick.AddListener(ShowAd);
        // Enable the button for users to click:
        _showAdButton.interactable = true;
        Debug.Log("HandleRewardedAdLoaded event received");
    }

    public void HandleRewardedAdFailedToLoad(object sender, AdFailureEventArgs args)
    {
        Debug.Log("HandleRewardedAdFailedToLoad event received with message: {args.Message}");
    }

    public void HandleReturnedToApplication(object sender, EventArgs args)
    {
        Debug.Log("HandleReturnedToApplication event received");
    }

    public void HandleLeftApplication(object sender, EventArgs args)
    {
        Debug.Log("HandleLeftApplication event received");
    }

    public void HandleAdClicked(object sender, EventArgs args)
    {
        Debug.Log("HandleAdClicked event received");
    }

    public void HandleRewardedAdShown(object sender, EventArgs args)
    {
        Debug.Log("HandleRewardedAdShown event received");
    }

    public void HandleRewardedAdDismissed(object sender, EventArgs args)
    {
        Debug.Log("HandleRewardedAdDismissed event received");
    }

    public void HandleImpression(object sender, ImpressionData impressionData)
    {
        var data = impressionData == null ? "null" : impressionData.rawData;
        Debug.Log("HandleImpression event received with data: {data}");
    }

    public void HandleRewarded(object sender, Reward args)
    {
        Debug.Log("HandleRewarded event received: amout = {args.amount}, type = {args.type}");
    }

    public void HandleRewardedAdFailedToShow(object sender, AdFailureEventArgs args)
    {
        Debug.Log("HandleRewardedAdFailedToShow event received with message: {args.Message}");
    }

    void OnDestroy()
    {
        //Clean up the ad
        rewardedAd.Destroy();
        // Clean up the button listeners:
        _showAdButton.onClick.RemoveAllListeners();
    }
}

Обратиться в службу поддержки

Предыдущая