Advice for combining Rewarded and Interstitial

Is there a recommended practice for using these two products from a code pov?

They both have a lot of duplicate code (e.g. InitializationComplete), so is it best practice to combine the code and make the portions that are specific to each product unique? (e.g. change LoadAd to LoadAdInterstitial and LoadAdRewarded).

Hey nobluff67, what version of the package are you using? :slight_smile:

1.0.5

I have not migrated to the ironsource yet as I am nearly ready to launch.

I have in the meantime combined the code and it seems to have solved an issue that I was experiencing.

Hello @nobluff67 ,

InitializationComplete is not really part of either interstitial or rewarded, this is part of a required step before loading any ad object, the initialization step.

Regarding combining Rewarded and Interstitial, I’d like to better understand your use case. Could you provide more insight in regards to what you are trying to achieve? Any code snippets to go with it would also help a lot.

Although the interfaces for these ad types are similar, they are generally used in different contexts within a game. One is mainly used for rewarding the user with something of worth within the context of the game, whereas an interstitial tends to show up between different segments of a game, the end of a level, etc. If you are using both, the lifecycle of each of those ads should be different, meaning the different calls and callbacks you make will very likely be different, potentially in different places.

Thank you for reaching out!

Here is the code, nothing special as I have just combined the two sample codes. I am using the reward from a menu button in order to reward the user with consumable rewards. The interstitial I am using after each 10 attempts (win or lose counts as an attempt).

using System;
using UnityEngine;
using Unity.Services.Core;
using Unity.Services.Mediation;

public class AdsController : MonoBehaviour
{
    public static AdsController Instance { get; private set; }

    [Header("Ad Unit Ids"), Tooltip("Android Ad Unit Ids")]
    public string androidAdUnitIdReward;
    [Tooltip("iOS Ad Unit Ids")] public string iosAdUnitIdReward;
    [Header("Ad Unit Ids"), Tooltip("Android Ad Unit Ids")]
    public string androidAdUnitIdInterstitial;
    [Tooltip("iOS Ad Unit Ids")] public string iosAdUnitIdInterstitial;

    [Header("Game Ids"),
     Tooltip("[Optional] Specifies the iOS GameId. Otherwise uses the GameId of the linked project.")]
    public string iosGameId;

    [Tooltip("[Optional] Specifies the Android GameId. Otherwise uses the GameId of the linked project.")]
    public string androidGameId;

    private bool musicWasOn;

    IRewardedAd m_RewardedAd;
    IInterstitialAd m_InterstitialAd;

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else if (Instance != this)
        {
            Destroy(this);
        }

//        DontDestroyOnLoad(this.gameObject);
    }

    async void Start()
    {
        try
        {
            await UnityServices.InitializeAsync(GetGameId());
            InitializationComplete();
        }
        catch (Exception e)
        {
            InitializationFailed(e);
        }
    }

    void OnDestroy()
    {
        m_RewardedAd?.Dispose();
        m_InterstitialAd?.Dispose();
    }

    InitializationOptions GetGameId()
    {
        var initializationOptions = new InitializationOptions();

#if UNITY_IOS
                if (!string.IsNullOrEmpty(iosGameId))
                {
                    initializationOptions.SetGameId(iosGameId);
                }
#elif UNITY_ANDROID
        if (!string.IsNullOrEmpty(androidGameId))
        {
            initializationOptions.SetGameId(androidGameId);
        }
#endif

        return initializationOptions;
    }


    public async void ShowRewarded()
    {
        Debug.Log("HEre");
        if (GlobalData.Instance.isMusicOn)
        {
            musicWasOn = true;
            GlobalVars.Instance.asMusic.mute = true;
        }

        if (m_RewardedAd?.AdState == AdState.Loaded)
        {
            try
            {
                var showOptions = new RewardedAdShowOptions {AutoReload = true};
                await m_RewardedAd.ShowAsync(showOptions);
                //GlobalData.Instance.temptext.text += "\nreward shown";
                if (musicWasOn)
                {
                    GlobalVars.Instance.asMusic.mute = false;
                }
            }
            catch (ShowFailedException e)
            {
                Debug.LogWarning($"Rewarded failed to show: {e.Message}");
                if (musicWasOn)
                {
                    GlobalVars.Instance.asMusic.mute = false;
                }
            }
        }
        else
        {
            //GlobalData.Instance.temptext.text += "\nno video: " + m_RewardedAd?.AdState;
            if (musicWasOn)
            {
                GlobalVars.Instance.asMusic.mute = false;
            }

        }
    }

    public async void ShowRewardedWithOptions()
    {
        if (m_RewardedAd?.AdState == AdState.Loaded)
        {
            try
            {
                //Here we provide a user id and custom data for server to server validation.
                RewardedAdShowOptions showOptions = new RewardedAdShowOptions();
                showOptions.AutoReload = true;
                S2SRedeemData s2SData;
                s2SData.UserId = "my cool user id";
                s2SData.CustomData = "{\"reward\":\"Gems\",\"amount\":20}";
                showOptions.S2SData = s2SData;

                await m_RewardedAd.ShowAsync(showOptions);
                Debug.Log("Rewarded Shown!");
                if (musicWasOn)
                {
                    GlobalVars.Instance.asMusic.mute = false;
                }
            }
            catch (ShowFailedException e)
            {
                Debug.LogWarning($"Rewarded failed to show: {e.Message}");
                if (musicWasOn)
                {
                    GlobalVars.Instance.asMusic.mute = false;
                }
            }
        }
    }

    async void LoadAdReward()
    {
        try
        {
            await m_RewardedAd.LoadAsync();
        }
        catch (LoadFailedException)
        {
            // We will handle the failure in the OnFailedLoad callback
        }
    }
   
    void InitializationComplete()
    {
        MediationService.Instance.ImpressionEventPublisher.OnImpression += ImpressionEvent;

        switch (Application.platform)
        {
            case RuntimePlatform.Android:
                //GlobalData.Instance.temptext.text += "\n android - init reward";
                m_InterstitialAd = MediationService.Instance.CreateInterstitialAd(androidAdUnitIdInterstitial);
                m_RewardedAd = MediationService.Instance.CreateRewardedAd(androidAdUnitIdReward);
                break;

            case RuntimePlatform.IPhonePlayer:
                m_InterstitialAd = MediationService.Instance.CreateInterstitialAd(iosAdUnitIdInterstitial);
                //GlobalData.Instance.temptext.text += "\n apple - init reward";
                m_RewardedAd = MediationService.Instance.CreateRewardedAd(iosAdUnitIdReward);
                break;
            case RuntimePlatform.WindowsEditor:
            case RuntimePlatform.OSXEditor:
            case RuntimePlatform.LinuxEditor:
                m_InterstitialAd = MediationService.Instance.CreateInterstitialAd(!string.IsNullOrEmpty(androidAdUnitIdInterstitial) ? androidAdUnitIdInterstitial : iosAdUnitIdInterstitial);
                m_RewardedAd =
                    MediationService.Instance.CreateRewardedAd(!string.IsNullOrEmpty(androidAdUnitIdReward)
                        ? androidAdUnitIdReward
                        : iosAdUnitIdReward);
                break;
            default:
                Debug.LogWarning("Mediation service is not available for this platform:" + Application.platform);
                return;
        }

        m_RewardedAd.OnLoaded += AdLoadedReward;
        m_RewardedAd.OnFailedLoad += AdFailedLoadReward;
        m_RewardedAd.OnUserRewarded += UserRewarded;
        m_RewardedAd.OnClosed += AdClosedReward;
       
        m_InterstitialAd.OnLoaded += AdLoadedInterstitial;
        m_InterstitialAd.OnFailedLoad += AdFailedLoadInterstitial;
        m_InterstitialAd.OnClosed += AdClosedInterstitial;

        LoadAdReward();
        LoadAdInterstitial();
    }

    void InitializationFailed(Exception error)
    {
        SdkInitializationError initializationError = SdkInitializationError.Unknown;
        if (error is InitializeFailedException initializeFailedException)
        {
            initializationError = initializeFailedException.initializationError;
        }

        //GlobalData.Instance.temptext.text += "\n - init fail reward";

        Debug.Log($"Initialization Failed: {initializationError}:{error.Message}");
    }

    void UserRewarded(object sender, RewardEventArgs e)
    {
        MenuSystem.Instance.RewardsCalc("R");
        if (musicWasOn)
        {
            GlobalVars.Instance.asMusic.mute = false;
        }

        //Debug.Log($"User Rewarded! Type: {e.Type} Amount: {e.Amount}");
    }

    void AdClosedReward(object sender, EventArgs args)
    {
        Debug.Log("Rewarded Closed! Loading Ad...");
        if (musicWasOn)
        {
            GlobalVars.Instance.asMusic.mute = false;
        }
    }

    void AdLoadedReward(object sender, EventArgs e)
    {
        //GlobalData.Instance.temptext.text += "\nad loaded - reward";
    }

    void AdFailedLoadReward(object sender, LoadErrorEventArgs e)
    {
        //GlobalData.Instance.temptext.text += "\nad failed loaded - reward: " + e.Message;
        Debug.Log(e.Message);
    }

    void ImpressionEvent(object sender, ImpressionEventArgs args)
    {
        if (musicWasOn)
        {
            GlobalVars.Instance.asMusic.mute = false;
        }

        var impressionData = args.ImpressionData != null ? JsonUtility.ToJson(args.ImpressionData, true) : "null";
    }

   
            public async void ShowInterstitial()
        {
            if (GlobalData.Instance.isMusicOn)
            {
                musicWasOn = true;
                GlobalVars.Instance.asMusic.mute = true;
            }

            if (m_InterstitialAd?.AdState == AdState.Loaded)
            {
                try
                {

                    var showOptions = new InterstitialAdShowOptions { AutoReload = true };
                    await m_InterstitialAd.ShowAsync(showOptions);
//                    Debug.Log("Interstitial Shown!");
                    if (musicWasOn)
                    {
                        GlobalVars.Instance.asMusic.mute = false;
                    }
                }
                catch (ShowFailedException e)
                {
                    Debug.Log($"Interstitial failed to show : {e.Message}");
                    if (musicWasOn)
                    {
                        GlobalVars.Instance.asMusic.mute = false;
                    }
                }
            }
            else
            {
                if (GlobalData.Instance.isMusicOn)
                {
                    musicWasOn = true;
                    GlobalVars.Instance.asMusic.mute = true;
                }
            }
        }

        async void LoadAdInterstitial()
        {
            try
            {
                await m_InterstitialAd.LoadAsync();
            }
            catch (LoadFailedException)
            {
                // We will handle the failure in the OnFailedLoad callback
            }
        }
        void AdClosedInterstitial(object sender, EventArgs args)
        {
//            Debug.Log("Interstitial Closed! Loading Ad...");                   
            if (musicWasOn)
            {
                GlobalVars.Instance.asMusic.mute = false;
            }

        }

        void AdLoadedInterstitial(object sender, EventArgs e)
        {
            //GlobalData.Instance.temptext.text += "\nad loaded - inter";
        }

        void AdFailedLoadInterstitial(object sender, LoadErrorEventArgs e)
        {
            //GlobalData.Instance.temptext.text += "\nad failed loaded - inter";
            //Debug.Log(e.Message);
        }

}

I am using ShowInterstitial and ShowRewarded.

The issue I was having has been resolved by combining the code.

The only thing I am not sure about now is what to do when a adload has failed. I am not sure if I should attempt to loadad in the failed event.