Skip to content

Instantly share code, notes, and snippets.

@YoshihideSogawa
Last active May 17, 2016 09:15
Show Gist options
  • Save YoshihideSogawa/b2aa090c67b89b9aac66 to your computer and use it in GitHub Desktop.
Save YoshihideSogawa/b2aa090c67b89b9aac66 to your computer and use it in GitHub Desktop.
UnityAdsをとりあえず実装してみた時に出来たコード
using UnityEngine;
using System.Collections;
using UnityEngine.Advertisements;
using UnityEngine.Events;
/// <summary>
/// Unity Adsを制御するクラスです。
/// </summary>
public class UnityAdsController : MonoBehaviour {
/// <summary>
/// 表示する広告のタイプ
/// </summary>
public enum PlacementId {
// 通常の動画
video,
// リワード動画(スキップ不可)
rewardedVideo
}
/// <summary>
/// 表示する広告のタイプ
/// </summary>
[SerializeField]
private PlacementId placementId;
/// <summary>
/// 何も問題がない
/// </summary>
public const int NONE = -1;
/// <summary>
/// 非サポート
/// </summary>
public const int NOT_SUPPORTED = 0;
/// <summary>
/// 通信エラー、広告ブロックなどで読み込みに失敗
/// </summary>
public const int LOAD_FAILED = 1;
/// <summary>
/// 広告スキップ
/// </summary>
public const int SKIPPED = 2;
/// <summary>
/// Android側のGame ID
/// </summary>
[SerializeField]
private string GameIdAndroid;
/// <summary>
/// iOS側のGame ID
/// </summary>
[SerializeField]
private string GameIdIOS;
/// <summary>
/// 表示の完了を通知します。
/// </summary>
public UnityEvent OnSuccess;
/// <summary>
/// 表示の失敗を通知します。
/// </summary>
public FailureEvent OnFailure;
/// <summary>
/// 広告を読み込みます。
/// </summary>
public void LoadAd() {
if (Advertisement.isSupported) {
// Unity Adsの内部でやっている処理を持ってきた
// こうすることで一度しかできないInitの失敗を防げる可能性が上がる
if (Application.internetReachability == NetworkReachability.NotReachable) {
if (OnFailure != null) {
OnFailure.Invoke (LOAD_FAILED);
}
return;
}
#if UNITY_ANDROID
Advertisement.Initialize (GameIdAndroid);
#elif UNITY_IOS
Advertisement.Initialize (GameIdIOS);
#endif
} else {
if (OnFailure != null) {
OnFailure.Invoke (NOT_SUPPORTED);
}
}
#if UNITY_EDITOR
Debug.Log("Unity Ads Loaded.");
#endif
}
/// <summary>
/// 広告の表示を行います。
/// </summary>
public void ShowAd() {
string placementIdStr = placementId.ToString ();
if (Advertisement.IsReady (placementIdStr)) {
Advertisement.Show (placementIdStr, new ShowOptions{
resultCallback = result => {
switch(result) {
case ShowResult.Finished:
if(OnSuccess != null){
OnSuccess.Invoke();
}
break;
case ShowResult.Failed:
if(OnFailure != null){
OnFailure.Invoke(LOAD_FAILED);
}
break;
case ShowResult.Skipped:
if(OnFailure != null){
OnFailure.Invoke (SKIPPED);
}
break;
}
}
});
} else {
if (OnFailure != null) {
OnFailure.Invoke (LOAD_FAILED);
}
}
#if UNITY_EDITOR
Debug.Log("Unity Ads Shown.");
#endif
}
/// <summary>
/// 表示失敗時のインスペクタ用クラス
/// </summary>
[System.Serializable]
public class FailureEvent : UnityEvent<int>{}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment