动物城-别人写好的广告代码
别人写的广告代码
- 里面有
facebook
和google
的广告 - 还有
facebook
,google
,twitter
的分享
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using AudienceNetwork;
/// <summary>
/// 广告管理器
/// </summary>
public class AdMgr : MonoBehaviour
{
public static AdMgr Instance;
/// <summary>
/// 下面的广告
/// </summary>
private AdView adView;
/// <summary>
/// 过年的广告
/// </summary>
private InterstitialAd interstitialAd;
private RewardedVideoAd rewardVideoAd;
private const string appId = "333019068083280";
private const string adId = "333019068083280_404165154302004";
private const string rewardId = "333019068083280_404165254301994";
private const string interstitialId = "333019068083280_406818390703347";
//private const string testAppId = "ca-app-pub-3940256099942544~3347511713";
//private const string testBannerId = "ca-app-pub-3940256099942544/6300978111";
//private const string testPassLevelId = "ca-app-pub-3940256099942544/1033173712";
//private const string testRewardId = "ca-app-pub-3940256099942544/5224354917";
Texture2D texShareImage;
private Queue<System.Action> triggerQueue = new Queue<System.Action>();
private void Start()
{
Instance = this;
Facebook.Unity.FB.Init();
TwitterKit.Unity.Twitter.Init();
//AdSettings.SetIsChildDirected(true);
//把要分享的图片放到指定的位置
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);
}
//初始化可能要用到的广告
AdMgr.Instance.InitPassLevelAd();
AdMgr.Instance.InitRewardAd();
}
private string getShareImagePath(string lan)
{
return Application.persistentDataPath + "/" + lan + ".png";
}
private bool triggerRewardSucc = false;
private bool triggerRewardFail = false;
private bool triggerPassLevel = false;
private void Update()
{
if (triggerRewardSucc)
{
rewardSuccAct?.Invoke();
rewardSuccAct = null;
triggerRewardSucc = false;
rewardFailAct = null;
}
if (triggerRewardFail)
{
rewardFailAct?.Invoke();
rewardFailAct = null;
triggerRewardFail = false;
rewardSuccAct = null;
}
if (triggerPassLevel)
{
passLevelAct?.Invoke();
passLevelAct = null;
triggerPassLevel = false;
}
while (triggerQueue.Count > 0)
{
triggerQueue.Dequeue()?.Invoke();
}
}
private bool rewardVideoAdLoaded = false;
private int tryReloadAgain = 3;
private void DisposeRewardAd(){
if (this.rewardVideoAd != null)
{
Debug.Log("销毁Reward视频数据");
this.rewardVideoAd.Dispose();
this.rewardVideoAd = null;
}
}
public void InitRewardAd()
{
if(this.rewardVideoAd != null)
{
//TODO : 防止重复加载,加载前需要保证历史数据已清理
Debug.Log("视频加载中,或已加载");
return;
}
Debug.Log("开始加载视频: " + tryReloadAgain);
this.rewardVideoAdLoaded = false;
rewardVideoAd = new RewardedVideoAd(rewardId);
rewardVideoAd.Register(this.gameObject);
rewardVideoAd.RewardedVideoAdDidLoad = delegate ()
{
Debug.Log("RewardedVideo ad loaded.");
rewardVideoAdLoaded = true;
};
rewardVideoAd.RewardedVideoAdDidFailWithError = delegate (string error)
{
Debug.Log("RewardedVideoAdDidFailWithError: " + error);
triggerQueue.Enqueue(() =>
{
Debug.Log("奖励广告加载失败" + error);
ShowAdFailed();
rewardFailAct = null;
rewardSuccAct = null;
tryReloadAgain--;
if (tryReloadAgain > 0)
{
DisposeRewardAd();
InitRewardAd();
}
});
};
rewardVideoAd.RewardedVideoAdWillLogImpression = delegate ()
{
Debug.Log("RewardedVideoAdWillLogImpression.");
//Debug.Log(JsonUtility.ToJson(rewardVideoAd.RewardData));
//if (this.rewardVideoAd != null)
//{
// string type = rewardVideoAd.RewardData.UserId;
// double amount = double.Parse(rewardVideoAd.RewardData.Currency);
// Debug.Log("玩家看完了广告, 得到的是" + type + ":" + amount);
// if (rewardSuccAct != null && amount >= 10)
// {
// Debug.Log("触发了广告奖励");
// //StartCoroutine(waitRewardAct());
// if (rewardSuccAct != null)
// triggerRewardSucc = true;
// }
//}
};
rewardVideoAd.RewardedVideoAdDidClick = delegate ()
{
Debug.Log("RewardedVideo ad clicked.");
};
rewardVideoAd.RewardedVideoAdWillClose = delegate ()
{
Debug.Log("RewardedVideoAdWillClose.");
//Debug.Log(JsonUtility.ToJson(rewardVideoAd.RewardData));
};
rewardVideoAd.RewardedVideoAdDidClose = delegate ()
{
Debug.Log("RewardedVideoAdDidClose.");
if (rewardSuccAct != null)
{
Debug.Log("触发了广告奖励");
//StartCoroutine(waitRewardAct());
if (rewardSuccAct != null)
triggerRewardSucc = true;
}
tryReloadAgain = 3;
this.DisposeRewardAd();
this.InitRewardAd();
BubbleTrack.Instance.OnShowPassLevel();
};
rewardVideoAd.RewardedVideoAdDidSucceed = delegate {
Debug.Log("RewardedVideoAdDidSucceed.");
};
rewardVideoAd.RewardedVideoAdDidFail = delegate {
Debug.Log("RewardedVideoAdDidFail.");
};
rewardVideoAd.RewardedVideoAdActivityDestroyed = delegate {
Debug.Log("RewardedVideoAdActivityDestroyed.");
};
rewardVideoAd.LoadAd();
}
private System.Action rewardSuccAct = null;
private System.Action rewardFailAct = null;
public bool ShowRewardAd(System.Action succAct, System.Action failAct)
{
rewardSuccAct = succAct;
rewardFailAct = failAct;
#if UNITY_EDITOR
//windows里直接播放回调不等了
triggerRewardSucc = true;
#else
if (rewardVideoAd != null && this.rewardVideoAdLoaded)
{
Debug.Log("reward加载完了,播放它");
this.rewardVideoAd.Show();
this.rewardVideoAdLoaded = false;
return true;
}
else
{
Debug.Log("还没加载完呢,啥都不做, 等待加载完成播放");
if(tryReloadAgain <= 0){
Debug.Log("失败多次,重新发起加载请求!");
tryReloadAgain = 3;
DisposeRewardAd();
InitRewardAd();
}
//StartCoroutine(waitForLoadRewardOver());
if (rewardFailAct != null)
{
triggerRewardFail = true;
}
}
#endif
return false;
}
/// <summary>
/// 等待加载完奖励广告. 如果两秒内加载不了. 那就放弃并执行回调
/// </summary>
/// <returns></returns>
IEnumerator waitForLoadRewardOver()
{
int i = 0;
while (this.rewardVideoAdLoaded == false)
{
i++;
Debug.Log("等下一帧或许加载好了");
yield return null;
if (i > 120)
{
Debug.Log("过了两秒也没有加载成功");
ShowAdFailed();
if (rewardFailAct != null)
{
triggerRewardFail = true;
}
yield break;
}
}
this.rewardVideoAd.Show();
this.rewardVideoAdLoaded = false;
}
/// <summary>
/// 关闭广告之后, 回来的时候要等几帧再执行回调, 否则会出现闪退.
/// </summary>
/// <returns></returns>
/// <summary>
/// 初始化过关或者长时间未动的广告, 六秒玩家无操作就出现广告
/// </summary>
private bool interstitialAdLoaded = false;
public void InitPassLevelAd()
{
return;
if (this.interstitialAd != null)
{
this.interstitialAd.Dispose();
this.interstitialAd = null;
this.interstitialAdLoaded = false;
}
this.interstitialAd = new InterstitialAd(interstitialId);
this.interstitialAd.Register(this.gameObject);
// Set delegates to get notified on changes or when the user interacts with the ad.
this.interstitialAd.InterstitialAdDidLoad = (delegate () {
Debug.Log("Interstitial ad loaded.");
this.interstitialAdLoaded = true;
});
interstitialAd.InterstitialAdDidFailWithError = (delegate (string error) {
Debug.Log("Interstitial ad failed to load with error: " + error);
triggerQueue.Enqueue(() =>
{
Debug.Log("passlevel广告加载失败" + error);
passLevelAct?.Invoke();
passLevelAct = null;
ShowAdFailed();
});
});
interstitialAd.InterstitialAdWillLogImpression = (delegate () {
Debug.Log("Interstitial ad logged impression.");
});
interstitialAd.InterstitialAdDidClick = (delegate () {
Debug.Log("Interstitial ad clicked.");
});
this.interstitialAd.interstitialAdDidClose = (delegate () {
Debug.Log("Interstitial ad did close.");
if (this.interstitialAd != null)
{
this.interstitialAd.Dispose();
}
passLevelAdShowing = false;
if (passLevelAct != null)
{
triggerPassLevel = true;
}
});
// Initiate the request to load the ad.
this.interstitialAd.LoadAd();
}
IEnumerator waitForLoadPassLevelAd()
{
int i = 0;
while (interstitialAd != null && interstitialAdLoaded == false)
{
i++;
Debug.Log("等下一帧或许加载好了");
yield return null;
if (i > 120)
{
yield break;
}
}
interstitialAd.Show();
interstitialAdLoaded = false;
}
public bool ShowPassLevelAd(bool show, System.Action act)
{
return false;
passLevelAct = act;
if (show)
{
if (passLevelAdShowing)
{
Debug.Log("已经在显示了. 不做处理");
if (passLevelAct != null)
{
triggerPassLevel = true;
}
return false;
}
if (interstitialAd != null && interstitialAdLoaded == true)
{
BubbleTrack.Instance.OnShowPassLevel();
passLevelAdShowing = true;
interstitialAd.Show();
interstitialAdLoaded = false;
return true;
}
//等了五关还是打不开, 就不用管了.
else
{
InitPassLevelAd();
//StartCoroutine(waitForLoadPassLevelAd());
if (passLevelAct != null)
{
triggerPassLevel = true;
}
}
}
else
{
passLevelAdShowing = false;
if (interstitialAd != null)
{
interstitialAd.Dispose();
interstitialAd = null;
}
InitPassLevelAd();
}
return false;
}
public void ShowBanner(bool show)
{
Debug.Log("初始化广告模块" + show);
if (show)
{
if (this.adView != null)
{
this.adView.Dispose();
}
this.adView = new AdView(adId, AdSize.BANNER_HEIGHT_50);
this.adView.Register(this.gameObject);
// Set delegates to get notified on changes or when the user interacts with the ad.
this.adView.AdViewDidLoad = delegate () {
Debug.Log("Banner loaded.");
this.adView.Show(AdPosition.BOTTOM);
Debug.Log("Banner Show.");
};
adView.AdViewDidFailWithError = delegate (string error) {
Debug.Log("Banner failed to load with error: " + error);
};
adView.AdViewWillLogImpression = delegate () {
Debug.Log("Banner logged impression.");
};
adView.AdViewDidClick = delegate () {
Debug.Log("Banner clicked.");
};
// Initiate a request to load an ad.
adView.LoadAd();
}
else
{
if (adView != null)
{
adView.Dispose();
}
}
}
int _passCount = 0;
System.Action passLevelAct = null;
private bool passLevelAdShowing = false;
public void OnPassLevel(System.Action act)
{
_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 = "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 = "تنبيه! اصدقاء الغابة بانتظارك لانقاذهم تعال وحمل لعبة اصدقاء الغابة الان و اكتشف اسرار هذه الحيوانات اللطيفة ! :-)";
}
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;
DisposeRewardAd();
InitRewardAd();
}
}
return true;
//return rewardVideoAdLoaded;
}
}