Instantly share code, notes, and snippets.

Embed
What would you like to do?
Unity Monetization SDK 3.0 で動画広告を表示するサンプルスクリプト(コールバックにUnityEventをつかったバージョン)
using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Monetization;
public class VideoAdsExampleScript : MonoBehaviour
{
[SerializeField, Header("テストモード")] private bool _testMode;
private const string IosGameId = "2942932";
private const string AndroidGameId = "2942930";
private const string PlacementId = "video";
private string _gameId = "";
private ShowAdCallbacks _showAdCallbacks;
[Header("指定したPlacement IDの広告表示準備ができたら呼ばれるコールバック")]
public UnityEvent PlacementContentReadyCallback;
[Header("広告の視聴が成功したら呼ばれるコールバック")] public UnityEvent AdFinishedCallback;
[Header("広告の視聴をスキップしたら呼ばれるコールバック")] public UnityEvent AdSkippedCallback;
[Header("広告の視聴が失敗したら呼ばれるコールバック")] public UnityEvent AdFailedCallback;
private void Start()
{
InitUnityAds();
}
/// <summary>
/// Monetization Service の初期化
/// 初期化とコールバックの設定
/// </summary>
private void InitUnityAds()
{
if (Monetization.isInitialized || !Monetization.isSupported) return;
#if UNITY_IOS
_gameId = IosGameId;
#elif UNITY_ANDROID
_gameId = AndroidGameId;
#endif
Monetization.Initialize(_gameId, _testMode);
Monetization.onPlacementContentReady += OnPlacementContentReady;
_showAdCallbacks = new ShowAdCallbacks {finishCallback = OnAdFinish};
}
/// <summary>
/// 指定したPlacement IDの広告表示準備ができたら呼ばれるコールバック
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnPlacementContentReady(object sender, PlacementContentReadyEventArgs e)
{
if (!e.placementId.Equals(PlacementId)) return;
PlacementContentReadyCallback.Invoke();
}
/// <summary>
/// 広告の視聴が終わったら呼ばれるコールバック
/// </summary>
/// <param name="result"></param>
private void OnAdFinish(ShowResult result)
{
switch (result)
{
case ShowResult.Finished:
AdFinishedCallback.Invoke();
break;
case ShowResult.Skipped:
AdSkippedCallback.Invoke();
break;
case ShowResult.Failed:
AdFailedCallback.Invoke();
break;
default:
throw new ArgumentOutOfRangeException(nameof(result), result, null);
}
}
/// <summary>
/// 広告を表示する関数
/// </summary>
public void ShowVideoAd()
{
if (!Monetization.IsReady(PlacementId))
{
Debug.LogFormat("Placement ID:\"{0}\" is not ready", PlacementId);
return;
}
var showAdPlacementContent = Monetization.GetPlacementContent(PlacementId) as ShowAdPlacementContent;
showAdPlacementContent?.Show(_showAdCallbacks);
}
private void OnDestroy()
{
Monetization.onPlacementContentReady -= OnPlacementContentReady;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment