项目中集成了ADTiming的代码
集成了一个广告管理的类
代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 广告管理器
/// </summary>
public class AdMgr : MonoBehaviour
{
public static AdMgr Instance;
// AdTiming的设置
private string AdTimingAppKey = "BL5YEWDo6tvt08BsprSpZugluKsVDcBa";
private string BannerPlacementId = "8405";
private bool isWatchAdSuccess = false;
Texture2D texShareImage;
private void Awake()
{
Instance = this;
}
private void Start()
{
Om.Agent.init(AdTimingAppKey);
OmEvents.onSdkInitSuccessEvent += SdkInitSuccessEvent;
OmEvents.onSdkInitFailedEvent += SdkInitFailedEvent;
//FaceBook和TwitterKit初始化
Facebook.Unity.FB.Init();
TwitterKit.Unity.Twitter.Init();
//把要分享的图片放到指定的位置
if (!System.IO.File.Exists(getShareImagePath("en")))
{
//如果找到这张图片就复制一次。
var temp = Resources.Load<TextAsset>("en");
System.IO.File.WriteAllBytes(getShareImagePath("en"), temp.bytes);
}
if (!System.IO.File.Exists(getShareImagePath("ar")))
{
//如果找到这张图片就复制一次。
var temp = Resources.Load<TextAsset>("ar");
System.IO.File.WriteAllBytes(getShareImagePath("ar"), temp.bytes);
}
// 接收事件
AddEvent();
}
/// <summary>
/// sdk初始化成功
/// </summary>
void SdkInitSuccessEvent()
{
GameLog.Instance.Log("AdTiming Sdk Init Success");
var is_init = Om.Agent.isInitialized();
Debug.Log(is_init);
}
//Receive message when sdk init failed
/// <summary>
/// sdk初始化失败
/// </summary>
/// <param name="error"></param>
void SdkInitFailedEvent(string error)
{
GameLog.Instance.Log("AdTiming Sdk Init Error " + error);
}
private void Update()
{
}
void AddEvent()
{
// 接收横幅广告事件
OmEvents.onBannerLoadSuccessEvent += BannerLoadSuccessEvent;
OmEvents.onBannerLoadFailedEvent += BannerLoadFailedEvent;
OmEvents.onBannerClickedEvent += BannerClickedEvent;
// 接收插页广告事件
OmEvents.onInterstitialAvailabilityChangedEvent += InterstitialAdAvailabilityChangedEvent;
OmEvents.onInterstitialShowedEvent += InterstitialAdShowedEvent;
OmEvents.onInterstitialShowFailedEvent += InterstitialAdShowFailedEvent;
OmEvents.onInterstitialClickedEvent += InterstitialAdClickedEvent;
OmEvents.onInterstitialClosedEvent += InterstitialAdClosedEvent;
// 接收激励广告事件
OmEvents.onRewardedVideoAvailabilityChangedEvent += RewardedVideoAvailabilityChangedEvent;
OmEvents.onRewardedVideoShowedEvent += RewardedVideoAdShowedEvent;
OmEvents.onRewardedVideoShowFailedEvent += RewardedVideoAdShowFailedEvent;
OmEvents.onRewardedVideoStartedEvent += RewardedVideoAdStartedEvent;
OmEvents.onRewardedVideoEndedEvent += RewardedVideoAdEndedEvent;
OmEvents.onRewardedVideoRewardedEvent += RewardedVideoAdRewardedEvent;
OmEvents.onRewardedVideoClickedEvent += RewardedVideoAdClickedEvent;
OmEvents.onRewardedVideoClosedEvent += RewardedVideoAdClosedEvent;
}
/*******************************************************/
/************* AdTiming 广告事件 ***************/
/*******************************************************/
//========================================横幅广告===============================================================
// 接收横幅广告事件
void BannerLoadSuccessEvent()
{
}
/// <summary>
/// 横幅广告load失败的事件
/// </summary>
/// <param name="error"></param>
void BannerLoadFailedEvent(string error)
{
ShowAdFailed();//接收横幅广告失败
Debug.Log("unity-script: I got BannerLoadFailedEvent: " + error);
}
void BannerClickedEvent()
{
Debug.Log("unity-script: I got BannerClickedEvent");
}
//========================================插页广告===============================================================
// 接收插页广告事件
void InterstitialAdAvailabilityChangedEvent(bool available)
{
Debug.Log("unity-script: I got InterstitialAdReadyEvent: " + available);
}
void InterstitialAdShowFailedEvent(string error)
{
InterstitialFailAct?.Invoke();
InterstitialFailAct = null;
InterstitialSuccAct = null;
ShowAdFailed();//接收插页广告失败
Debug.Log("unity-script: I got InterstitialAdShowFailedEvent, code: " + error);
}
void InterstitialAdClickedEvent(string scene)
{
Debug.Log("unity-script: I got InterstitialAdClickedEvent: " + scene);
}
void InterstitialAdShowedEvent(string scene)
{
InterstitialSuccAct?.Invoke();
InterstitialSuccAct = null;
InterstitialFailAct = null;
Debug.Log("unity-script: I got InterstitialAdOpenedEvent: " + scene);
}
void InterstitialAdClosedEvent(string scene)
{
Debug.Log("unity-script: I got InterstitialAdClosedEvent: " + scene);
}
//========================================激励广告==========================================================
/// <summary>
/// 激励广告可用的实践
/// </summary>
/// <param name="available"></param>
void RewardedVideoAvailabilityChangedEvent(bool available)
{
Debug.Log("有效==unity-script: I got RewardedVideoAvailabilityChangedEvent, value = " + available);
if (isWatchAdSuccess == false && available == true)
{
rewardFailAct?.Invoke();
rewardFailAct = null;
rewardSuccAct = null;
}
else
{
}
}
/// <summary>
/// 广告显示的事件
/// </summary>
/// <param name="scene"></param>
void RewardedVideoAdShowedEvent(string scene)
{
Debug.Log("unity-script: I got RewardedVideoAdOpenedEvent: " + scene);
}
/// <summary>
/// 激励广告播放失败
/// </summary>
/// <param name="error"></param>
void RewardedVideoAdShowFailedEvent(string error)
{
rewardFailAct?.Invoke();
rewardFailAct = null;
rewardSuccAct = null;
ShowAdFailed();//接收插页广告失败
Debug.Log("失败unity-script: I got RewardedVideoAdShowFailedEvent, error: " + error);
}
/// <summary>
/// 获得奖励的通知
/// </summary>
/// <param name="scene"></param>
void RewardedVideoAdRewardedEvent(string scene)
{
rewardSuccAct?.Invoke();
rewardSuccAct = null;
rewardFailAct = null;
isWatchAdSuccess = true;
Debug.Log("获得奖励unity-script: I got RewardedVideoAdRewardedEvent: " + scene);
}
/// <summary>
/// 激励广告关闭的事件
/// </summary>
/// <param name="scene"></param>
void RewardedVideoAdClosedEvent(string scene)
{
if(isWatchAdSuccess == false)
{
rewardFailAct?.Invoke();
rewardFailAct = null;
rewardSuccAct = null;
}
Debug.Log("关闭unity-script: I got RewardedVideoAdClosedEvent: " + scene);
}
/// <summary>
/// 激励广告开始的事件
/// </summary>
/// <param name="scene"></param>
void RewardedVideoAdStartedEvent(string scene)
{
Debug.Log("开始unity-script: I got RewardedVideoAdStartedEvent: " + scene);
}
/// <summary>
/// 激励广告播放结束
/// </summary>
/// <param name="scene"></param>
void RewardedVideoAdEndedEvent(string scene)
{
Debug.Log("结束unity-script: I got RewardedVideoAdEndedEvent: " + scene);
}
/// <summary>
/// 激励广告点击的事件
/// </summary>
/// <param name="scene"></param>
void RewardedVideoAdClickedEvent(string scene)
{
Debug.Log("unity-script: I got RewardedVideoAdClickedEvent, name = " + scene);
}
private string getShareImagePath(string lan)
{
GameLog.Instance.LogError(Application.persistentDataPath + "/" + lan + ".png");
return Application.persistentDataPath + "/" + lan + ".png";
}
private bool rewardVideoAdLoaded = false;
private int tryReloadAgain = 3;
private System.Action rewardSuccAct = null;
private System.Action rewardFailAct = null;
private System.Action InterstitialSuccAct = null;
private System.Action InterstitialFailAct = null;
/// <summary>
/// 激励广告
/// </summary>
/// <param name="succAct"></param>
/// <param name="failAct"></param>
/// <returns></returns>
public bool ShowRewardAd(System.Action succAct, System.Action failAct)
{
rewardSuccAct = succAct;
rewardFailAct = failAct;
isWatchAdSuccess = false;
#if UNITY_EDITOR
//windows里直接播放回调不等了
rewardSuccAct?.Invoke();
rewardSuccAct = null;
rewardFailAct = null;
isWatchAdSuccess = true;
#else
if (Om.Agent.isRewardedVideoReady())
{
Om.Agent.showRewardedVideo();
return true;
}
#endif
return false;
}
/// <summary>
/// 横幅广告
/// </summary>
/// <param name="show"></param>
public void ShowBanner(bool show)
{
Debug.Log("初始化广告模块" + show);
if (show)
{
GameLog.Instance.LogError("横幅广告显示============================");
Om.Agent.loadBanner(BannerPlacementId, AdSize.BANNER, BannerPostion.BOTTOM);
}
else
{
GameLog.Instance.LogError("隐藏横幅广告============================");
Om.Agent.destroyBanner(BannerPlacementId);
}
}
/// <summary>
/// 插页广告
/// </summary>
/// <returns></returns>
public bool ShowInterstitia(System.Action succAct, System.Action failAct)
{
InterstitialSuccAct = succAct;
InterstitialFailAct = failAct;
#if UNITY_EDITOR
//windows里直接播放回调不等了
InterstitialSuccAct?.Invoke();
InterstitialSuccAct = null;
InterstitialFailAct = null;
#else
if (Om.Agent.isInterstitialReady())
{
Om.Agent.showInterstitial();
return true;
}
#endif
return false;
}
/// <summary>
/// 不操作就弹广告的代码
/// </summary>
int _passCount = 0;
System.Action passLevelAct = null;
private bool passLevelAdShowing = false;
public void OnPassLevel(System.Action act)
{
return;
//_passCount++;
//passLevelAct = act;
//if (_passCount % 5 == 0 && _passCount > 4)
//{
// ShowPassLevelAd(true, act);
//}
//else
//{
// if (passLevelAct != null)
// {
// triggerPassLevel = true;
// }
//}
}
private FairyGUI.GLoader _imgAdFailedEn;
private FairyGUI.GLoader _imgAdFailedAr;
private int failedCount = 0;
public void ShowAdFailed()
{
if (failedCount > 4)
{
Debug.Log("ShowAdFailed 弹几次就得了");
//弹几次就得了
return;
}
failedCount++;
string url = null;
FairyGUI.GLoader img = null;
if (Language.English == (Language)PlayerPrefsManager.GetInt("language"))
{
url = "Connection Failed";
}
else
{
url = "Connection Failed_Ar";
}
if (url != null)
{
img = new FairyGUI.GLoader
{
url = url
};
var parent = FairyGUI.GRoot.inst;
parent.AddChild(img);
img.pivot = Vector2.one * 0.5f;
img.pivotAsAnchor = true;
img.image.pivot = Vector2.one * 0.5f;
img.position = new Vector2((parent.width - img.image.width) / 2.0f, parent.height / 2.0f);
img.gameObjectName = "gggnnn";
if (Language.English == (Language)PlayerPrefsManager.GetInt("language"))
{
_imgAdFailedEn = img;
}
else
{
_imgAdFailedAr = img;
}
}
if (Language.English == (Language)PlayerPrefsManager.GetInt("language"))
{
if (img != null)
_imgAdFailedEn = img;
_imgAdFailedEn.visible = true;
}
else
{
if (img != null)
_imgAdFailedAr = img;
_imgAdFailedAr.visible = true;
}
DelayCall(1.0f, img, (obj) =>
{
obj.visible = false;
});
}
public void DelayCall(float t, FairyGUI.GObject obj, System.Action<FairyGUI.GObject> act)
{
StartCoroutine(_delayCall(t, obj, act));
}
private IEnumerator _delayCall(float t, FairyGUI.GObject obj, System.Action<FairyGUI.GObject> act)
{
yield return new WaitForSeconds(t);
act?.Invoke(obj);
}
private string GooglePlayURL()
{
if ((Language)PlayerPrefsManager.GetInt("language") == Language.English)
{
return "https://play.google.com/store/apps/details?id=com.animalshooteren.redpencilart";
}
else
{
return "https://play.google.com/store/apps/details?id=com.animalshooteren.redpencilart";
}
}
public void ShareFacebook()
{
Debug.Log("打开facebook");
string content = "SOS! Your cute animal friends are waiting for you to rescue! Come and download Animal Topia TODAY to reveal more secrets behind this furry lttle world! :-) .";
if (Language.Arabic == (Language)PlayerPrefsManager.GetInt("language"))
{
content = "تنبيه! اصدقاء الغابة بانتظارك لانقاذهم تعال وحمل لعبة اصدقاء الغابة الان و اكتشف اسرار هذه الحيوانات اللطيفة ! :-)";
}
string imageIconUrl = "https://www.seeknpass.com/icon2.png";
Facebook.Unity.FB.ShareLink(
new System.Uri(GooglePlayURL()),
content,
content,
//new System.Uri("file://" + getShareImagePath()),
new System.Uri(imageIconUrl),
(Facebook.Unity.IShareResult r) =>
{
Debug.Log("分享成功");
});
}
private TwitterKit.Unity.TwitterSession _twitterSession = null;
/// <summary>
/// 分享1
/// </summary>
public void ShareTwitter()
{
Debug.Log("打开twitter");
//8nYG6E1js5OfttcdOUeyEB1kA
//TwitterKit.Unity.Twitter.Compose
if (_twitterSession == null)
{
TwitterKit.Unity.Twitter.LogIn(LoginCompleteWithCompose, (TwitterKit.Unity.ApiError error) =>
{
Debug.Log("login 错误错误错误???");
Debug.Log(error.message);
});
}
else
{
LoginCompleteWithCompose(_twitterSession);
}
}
public void LoginCompleteWithCompose(TwitterKit.Unity.TwitterSession session)
{
_twitterSession = session;
Debug.Log("session 是啥" + session);
Debug.Log(session.id);
Debug.Log(session.authToken);
Debug.Log(session.userName);
string content = "Animal Topia is a new gameplay of bubble shooter game. Come and download Animal Topia to reveal more secrets behind this furry little world!";
if (Language.Arabic == (Language)PlayerPrefsManager.GetInt("language"))
{
content = " معرفة الحيوانات مثيرة للاهتمام، واللعبة الغنية، والمدينة المبتكرة، كل ذلك في مدينة الحيوانات";
}
content = content + " " + GooglePlayURL();
//ScreenCapture.CaptureScreenshot("Screenshot.png");
//Debug.Log("Screenshot location=" + Application.persistentDataPath + "/Screenshot.png");
string imageUri = "file://" + getShareImagePath("en");
if ((Language)PlayerPrefsManager.GetInt("language") == Language.Arabic)
{
imageUri = "file://" + getShareImagePath("ar");
}
//string imageIconUrl = "https://www.seeknpass.com/icon2.png";
TwitterKit.Unity.Twitter.Compose(session,
imageUri,
content,
new string[] { "#AnimalTopia" },
(string tweetId) =>
{
Debug.Log("twitter分享成功了了了了");
Debug.Log("分享twitter成功, tweetId=" + tweetId);
},
(TwitterKit.Unity.ApiError error) =>
{
Debug.Log("twitter分享失败了了了了");
Debug.Log("twitter分享失败" + error);
},
() =>
{
Debug.Log("取消分享twitter");
}
);
}
public void RateGooglePlay()
{
if (PlayerPrefs.GetInt("hasRate", 0) > 0)
{
//领取过了
Application.OpenURL(GooglePlayURL());
}
else
{
//GameController.instance.RefreshGold(1000);
PlayerPrefs.SetInt("hasRate", 1);
Application.OpenURL(GooglePlayURL());
}
}
public bool IsRewardAdAvailable()
{
//rewardVideoAdLoaded广告奖励是否被加载
if (rewardVideoAdLoaded == false)
{
if (tryReloadAgain <= 0)
{
Debug.Log("失败多次,重新发起加载请求!");
tryReloadAgain = 3;
}
}
return true;
}
}