Unity IronSource 腳本範例


建立時間: 2023年7月10日 09:46
更新時間: 2023年9月14日 08:38

說明

提供 IronSource 各式廣告的腳本範例。

若你尚未配置 IronSource 請先看 Unity 使用新廣告 IronSource 配置。

廣告管理器

廣告廣告管理器,用來管理廣告的功能,所有跟廣告有關的共用功能都添加在這裡。

AdManager.cs

using UnityEngine;

/// <summary>
/// 廣告管理器
/// </summary>
public class AdManager : MonoBehaviour
{
    /// <summary>
    /// 單例實體
    /// </summary>
    private static AdManager instance;

    public static AdManager Instance => instance;

    /// <summary>
    /// 廣告 App key 會自動識別裝置
    /// </summary>
    public static string APP_KEY => GetAppKey();

    private void Awake()
    {
        if (instance != null)
        {
            Destroy(gameObject);

            return;
        }
        instance = this;
        DontDestroyOnLoad(gameObject);

        InitializeAd();

        IronSourceEvents.onSdkInitializationCompletedEvent +=
            SdkInitializationCompletedEvent;
    }

    private void OnApplicationPause(bool pauseStatus)
    {
        // 通知廣告程式是否暫停
        IronSource.Agent.onApplicationPause(pauseStatus);
    }

    /// <summary>
    /// 取得裝置對應的 App key
    /// </summary>
    /// <returns></returns>
    private static string GetAppKey()
    {
        return Application.platform switch
        {
            RuntimePlatform.Android => "your_android_app_key",
            RuntimePlatform.IPhonePlayer => "your_iphone_app_key",
            // 在 Unity Editor 識別用
            RuntimePlatform.OSXEditor => "your_app_key",
            _ => "unsupported_platform",
        };
    }

    /// <summary>
    /// 初始化廣告
    /// </summary>
    private void InitializeAd()
    {
        IronSource.Agent.validateIntegration();
        IronSource.Agent.init(APP_KEY);
        IronSource.Agent.shouldTrackNetworkState(true);
    }

    /// <summary>
    /// 廣告初始化成功事件
    /// </summary>
    private void SdkInitializationCompletedEvent()
    {
        Debug.Log("IronSource Sdk Initialization Completed");
    }
}

我將它設為單例實體不會被摧毀,OnApplicationPause() 要確保在每個場景都跑。

橫幅廣告

橫幅廣告顯示在螢幕的頂部或底部,開啟後會一直顯示,直到它被摧毀或隱藏。

AdBanner.cs

using UnityEngine;

/// <summary>
/// 橫幅廣告
/// </summary>
public class AdBanner : MonoBehaviour
{
    /// <summary>
    /// 單例實體
    /// </summary>
    private static AdBanner instance;

    /// <summary>
    /// 廣告是否載入
    /// </summary>
    private static bool isLoaded = false;

    /// <summary>
    /// 單例實體
    /// </summary>
    public static AdBanner Instance => instance;

    /// <summary>
    /// 廣告是否載入
    /// </summary>
    public static bool IsLoaded => isLoaded;

    private void Awake()
    {
        if (instance != null)
        {
            Destroy(gameObject);

            return;
        }
        instance = this;
        DontDestroyOnLoad(gameObject);

        //Add AdInfo Banner Events
        IronSourceBannerEvents.onAdLoadedEvent += BannerOnAdLoadedEvent;
        IronSourceBannerEvents.onAdLoadFailedEvent += BannerOnAdLoadFailedEvent;
        IronSourceBannerEvents.onAdClickedEvent += BannerOnAdClickedEvent;
        IronSourceBannerEvents.onAdScreenPresentedEvent += BannerOnAdScreenPresentedEvent;
        IronSourceBannerEvents.onAdScreenDismissedEvent += BannerOnAdScreenDismissedEvent;
        IronSourceBannerEvents.onAdLeftApplicationEvent += BannerOnAdLeftApplicationEvent;
    }

    private void Start()
    {
        IronSource.Agent.loadBanner(
            IronSourceBannerSize.SMART, IronSourceBannerPosition.TOP);
    }

    private void OnDestroy()
    {
        if (instance != this)
        {
            return;
        }
        IronSourceBannerEvents.onAdLoadedEvent -= BannerOnAdLoadedEvent;
        IronSourceBannerEvents.onAdLoadFailedEvent -= BannerOnAdLoadFailedEvent;
        IronSourceBannerEvents.onAdClickedEvent -= BannerOnAdClickedEvent;
        IronSourceBannerEvents.onAdScreenPresentedEvent -= BannerOnAdScreenPresentedEvent;
        IronSourceBannerEvents.onAdScreenDismissedEvent -= BannerOnAdScreenDismissedEvent;
        IronSourceBannerEvents.onAdLeftApplicationEvent -= BannerOnAdLeftApplicationEvent;

        IronSource.Agent.destroyBanner();
    }

    /// <summary>
    /// Invoked once the banner has loaded
    /// </summary>
    /// <param name="adInfo">ad information</param>
    void BannerOnAdLoadedEvent(IronSourceAdInfo adInfo)
    {
        isLoaded = true;
        Debug.Log("Banner On Ad Loaded Event");
    }

    /// <summary>
    /// Invoked when the banner loading process has failed.
    /// </summary>
    /// <param name="ironSourceError">ironSource Error</param>
    void BannerOnAdLoadFailedEvent(IronSourceError ironSourceError)
    {
        Debug.Log("Banner On Ad Load Failed Event");
        IronSource.Agent.loadBanner(
            IronSourceBannerSize.SMART, IronSourceBannerPosition.TOP);
    }

    /// <summary>
    /// Invoked when end user clicks on the banner ad
    /// </summary>
    /// <param name="adInfo">ad information</param>
    void BannerOnAdClickedEvent(IronSourceAdInfo adInfo)
    {
        Debug.Log("Banner On Ad Clicked Event");
    }

    /// <summary>
    /// Notifies the presentation of a full screen content following user click
    /// </summary>
    /// <param name="adInfo">ad information</param>
    void BannerOnAdScreenPresentedEvent(IronSourceAdInfo adInfo)
    {
        Debug.Log("Banner On Ad Screen Presented Event");
    }

    /// <summary>
    /// Notifies the presented screen has been dismissed
    /// </summary>
    /// <param name="adInfo">ad information</param>
    void BannerOnAdScreenDismissedEvent(IronSourceAdInfo adInfo)
    {
        Debug.Log("Banner On Ad Screen Dismissed Event");
    }

    /// <summary>
    /// Invoked when the user leaves the app
    /// </summary>
    /// <param name="adInfo">ad information</param>
    void BannerOnAdLeftApplicationEvent(IronSourceAdInfo adInfo)
    {
        Debug.Log("Banner On Ad Left Application Event");
    }
}

我將它設為單例實體不會被摧毀。

需注意這行 IronSource.Agent.loadBanner(IronSourceBannerSize.SMART, IronSourceBannerPosition.TOP); 這行是載入廣告,讀者可能會需要調整尺寸和位置。

還有一點需注意 BannerOnAdLoadFailedEvent() 是廣告載入失敗觸發的事件,我在這裡又重新載入,讀者可以自行決定要如何處理。

獎勵廣告

獎勵廣告會播放比較久的廣告影片,當播放完畢後可以讓玩家獲得獎勵,獎勵項目可以由開發者決定。

AdRewarded.cs

using UnityEngine;

/// <summary>
/// 獎勵廣告,廣告秒數較長
/// </summary>
public class AdRewarded : MonoBehaviour
{
    /// <summary>
    /// 單例實體
    /// </summary>
    private static AdRewarded instance;

    /// <summary>
    /// 單例實體
    /// </summary>
    public static AdRewarded Instance => instance;

    private void Awake()
    {
        if (instance != null)
        {
            Destroy(gameObject);

            return;
        }
        instance = this;
        DontDestroyOnLoad(gameObject);

        //Add AdInfo Rewarded Video Events
        IronSourceRewardedVideoEvents.onAdOpenedEvent += RewardedVideoOnAdOpenedEvent;
        IronSourceRewardedVideoEvents.onAdClosedEvent += RewardedVideoOnAdClosedEvent;
        IronSourceRewardedVideoEvents.onAdAvailableEvent += RewardedVideoOnAdAvailable;
        IronSourceRewardedVideoEvents.onAdUnavailableEvent += RewardedVideoOnAdUnavailable;
        IronSourceRewardedVideoEvents.onAdShowFailedEvent +=
            RewardedVideoOnAdShowFailedEvent;
        IronSourceRewardedVideoEvents.onAdRewardedEvent += RewardedVideoOnAdRewardedEvent;
        IronSourceRewardedVideoEvents.onAdClickedEvent += RewardedVideoOnAdClickedEvent;
    }

    private void OnDestroy()
    {
        if (instance != this)
        {
            return;
        }
        IronSourceRewardedVideoEvents.onAdOpenedEvent -= RewardedVideoOnAdOpenedEvent;
        IronSourceRewardedVideoEvents.onAdClosedEvent -= RewardedVideoOnAdClosedEvent;
        IronSourceRewardedVideoEvents.onAdAvailableEvent -= RewardedVideoOnAdAvailable;
        IronSourceRewardedVideoEvents.onAdUnavailableEvent -= RewardedVideoOnAdUnavailable;
        IronSourceRewardedVideoEvents.onAdShowFailedEvent -=
            RewardedVideoOnAdShowFailedEvent;
        IronSourceRewardedVideoEvents.onAdRewardedEvent -= RewardedVideoOnAdRewardedEvent;
        IronSourceRewardedVideoEvents.onAdClickedEvent -= RewardedVideoOnAdClickedEvent;
    }

    /// <summary>
    /// Indicates that there’s an available ad.
    /// </summary>
    /// <param name="adInfo">Information about the ad that was loaded successfully</param>
    void RewardedVideoOnAdAvailable(IronSourceAdInfo adInfo)
    {
    }

    /// <summary>
    /// Indicates that no ads are available to be displayed
    /// </summary>
    void RewardedVideoOnAdUnavailable()
    {
    }

    /// <summary>
    /// The Rewarded Video ad view has opened. Your activity will loose focus.
    /// </summary>
    /// <param name="adInfo"></param>
    void RewardedVideoOnAdOpenedEvent(IronSourceAdInfo adInfo)
    {
        // 開啟遊戲靜音
    }

    /// <summary>
    /// The Rewarded Video ad view is about to be closed. Your activity will regain its focus.
    /// </summary>
    /// <param name="adInfo"></param>
    void RewardedVideoOnAdClosedEvent(IronSourceAdInfo adInfo)
    {
        Debug.Log("unity-script: I got RewardedVideoOnAdClosedEvent With AdInfo " +
            adInfo.ToString());

        // 關閉遊戲靜音

        IronSource.Agent.init(AdManager.APP_KEY, IronSourceAdUnits.REWARDED_VIDEO);
        IronSource.Agent.shouldTrackNetworkState(true);
    }

    /// <summary>
    /// The user completed to watch the video, and should be rewarded.
    /// When using server-to-server callbacks,
    /// you may ignore this event and wait for the ironSource server callback.
    /// </summary>
    /// <param name="placement">reward data</param>
    /// <param name="adInfo"></param>
    void RewardedVideoOnAdRewardedEvent(IronSourcePlacement placement, IronSourceAdInfo adInfo)
    {
        Debug.Log("unity-script: I got RewardedVideoOnAdRewardedEvent With Placement" +
            placement.ToString() + "And AdInfo " + adInfo.ToString());

        // 處理獎勵
    }

    /// <summary>
    /// The rewarded video ad was failed to show.
    /// </summary>
    /// <param name="error"></param>
    /// <param name="adInfo"></param>
    void RewardedVideoOnAdShowFailedEvent(IronSourceError error, IronSourceAdInfo adInfo)
    {
    }

    /// <summary>
    /// Invoked when the video ad was clicked.
    /// This callback is not supported by all networks, and we recommend using it only if
    /// it’s supported by all networks you included in your build.
    /// </summary>
    /// <param name="placement"></param>
    /// <param name="adInfo"></param>
    void RewardedVideoOnAdClickedEvent(
        IronSourcePlacement placement, IronSourceAdInfo adInfo)
    {
    }
}

我將它設為單例實體不會被摧毀。

需注意播放廣告時,讓遊戲靜音,才不會同時播放兩個聲音,還有就是處理獎勵機制,我都有在腳本註解該在什麼事件處理了,讀者可以參考看看,不一定要完全按照我的建議。

插頁式廣告

插頁式廣告會播放比較短的廣告影片,比較適合放在遊戲結束、或者是中場休息進廣告的機制,這不是為了獎勵而做的廣告,但你也可以給予小獎勵,沒有強制禁止不能給獎勵。

AdInterstitial.cs

using UnityEngine;

/// <summary>
/// 插頁式廣告
/// </summary>
public class AdInterstitial : MonoBehaviour
{
    /// <summary>
    /// 單例實體
    /// </summary>
    private static AdInterstitial instance;

    /// <summary>
    /// 單例實體
    /// </summary>
    public static AdInterstitial Instance => instance;

    private void Awake()
    {
        if (instance != null)
        {
            Destroy(gameObject);

            return;
        }
        instance = this;
        DontDestroyOnLoad(gameObject);

        IronSource.Agent.loadInterstitial();

        //Add AdInfo Interstitial Events
        IronSourceInterstitialEvents.onAdReadyEvent += InterstitialOnAdReadyEvent;
        IronSourceInterstitialEvents.onAdLoadFailedEvent += InterstitialOnAdLoadFailed;
        IronSourceInterstitialEvents.onAdOpenedEvent += InterstitialOnAdOpenedEvent;
        IronSourceInterstitialEvents.onAdClickedEvent += InterstitialOnAdClickedEvent;
        IronSourceInterstitialEvents.onAdShowSucceededEvent +=
            InterstitialOnAdShowSucceededEvent;
        IronSourceInterstitialEvents.onAdShowFailedEvent += InterstitialOnAdShowFailedEvent;
        IronSourceInterstitialEvents.onAdClosedEvent += InterstitialOnAdClosedEvent;
    }

    private void OnDestroy()
    {
        if (instance != this)
        {
            return;
        }
        IronSourceInterstitialEvents.onAdReadyEvent -= InterstitialOnAdReadyEvent;
        IronSourceInterstitialEvents.onAdLoadFailedEvent -= InterstitialOnAdLoadFailed;
        IronSourceInterstitialEvents.onAdOpenedEvent -= InterstitialOnAdOpenedEvent;
        IronSourceInterstitialEvents.onAdClickedEvent -= InterstitialOnAdClickedEvent;
        IronSourceInterstitialEvents.onAdShowSucceededEvent -=
            InterstitialOnAdShowSucceededEvent;
        IronSourceInterstitialEvents.onAdShowFailedEvent -= InterstitialOnAdShowFailedEvent;
        IronSourceInterstitialEvents.onAdClosedEvent -= InterstitialOnAdClosedEvent;
    }

    private void Start()
    {
        IronSource.Agent.loadInterstitial();
    }

    /// <summary>
    /// Invoked when the interstitial ad was loaded successfully.
    /// </summary>
    /// <param name="adInfo"></param>
    void InterstitialOnAdReadyEvent(IronSourceAdInfo adInfo)
    {
    }

    /// <summary>
    /// Invoked when the initialization process has failed.
    /// </summary>
    /// <param name="ironSourceError"></param>
    void InterstitialOnAdLoadFailed(IronSourceError ironSourceError)
    {
    }

    /// <summary>
    /// Invoked when the Interstitial Ad Unit has opened. This is the impression indication. 
    /// </summary>
    /// <param name="adInfo"></param>
    void InterstitialOnAdOpenedEvent(IronSourceAdInfo adInfo)
    {
        // 開啟遊戲靜音
    }

    /// <summary>
    /// Invoked when end user clicked on the interstitial ad
    /// </summary>
    /// <param name="adInfo"></param>
    void InterstitialOnAdClickedEvent(IronSourceAdInfo adInfo)
    {
    }

    /// <summary>
    /// Invoked when the ad failed to show.
    /// </summary>
    /// <param name="ironSourceError"></param>
    /// <param name="adInfo"></param>
    void InterstitialOnAdShowFailedEvent(
        IronSourceError ironSourceError, IronSourceAdInfo adInfo)
    {
    }

    /// <summary>
    /// Invoked when the interstitial ad closed and the user went back to the application screen.
    /// </summary>
    /// <param name="adInfo"></param>
    void InterstitialOnAdClosedEvent(IronSourceAdInfo adInfo)
    {
        // 關閉遊戲靜音
        IronSource.Agent.loadInterstitial();
    }

    /// <summary>
    /// Invoked before the interstitial ad was opened,
    /// and before the InterstitialOnAdOpenedEvent is reported.
    /// This callback is not supported by all networks, and we recommend using it only if
    /// it's supported by all networks you included in your build. 
    /// </summary>
    /// <param name="adInfo"></param>
    void InterstitialOnAdShowSucceededEvent(IronSourceAdInfo adInfo)
    {
    }
}

腳本邏輯類似獎勵廣告,我就不再贅述了。

觀看次數: 1130
adadvertisementbannerinterstitialironsourcerewardrewardedunity廣告
按讚追蹤 Enjoy 軟體 Facebook 粉絲專頁
每週分享資訊技術

一杯咖啡的力量,勝過千言萬語的感謝。

支持我一杯咖啡,讓我繼續創作優質內容,與您分享更多知識與樂趣!