I'm trying to add an Admob reward video ad to my android game made in Unity. The displays fine but when I close the ad, the reward is never given. I've tested the code in the function and the works fine so I think the problem is that is isn't gettting called. Can anyone help me?
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
using GoogleMobileAds;
using GoogleMobileAds.Api;
public class textEdit : MonoBehaviour
{
public Image lifeAdUI;
static Image lifeAdUIStat;
public Text adFailUI;
static Text adFailUIStat;
public Button lifeButton;
private static RewardBasedVideoAd videoAd;
static bool adTime = false;
static bool adPlaying = false;
static int pass = 0;
bool watched;
// Use this for initialisation
void Start()
{
Button btn = lifeButton.GetComponent<Button>();
btn.onClick.AddListener(VideoAd);
videoAd = RewardBasedVideoAd.Instance;
videoAd.OnAdFailedToLoad += HandleOnAdFailedToLoad;
videoAd.OnAdOpening += HandleOnAdOpening;
videoAd.OnAdClosed += HandleOnAdClosed;
videoAd.OnAdRewarded += HandleOnAdReward;
videoAd.OnAdLeavingApplication += HandleOnAdLeavingApplication;
videoAd.OnAdLoaded += HandleOnAdLoaded;
videoAd.OnAdStarted += HandleOnAdStarted;
lifeAdUIStat = lifeAdUI;
adFailUIStat = adFailUI;
}
public static void LoadVideoAd()
{
#if UNITY_EDITOR
string adUnitID = "unused";
#elif UNITY_ANDROID
string adUnitID = "ca-app-pub-3025391748532285/9122766975";
#elif UNITY_IPHONE
string adUnitID = "";
#else
string adUnitID = "unexpected_platform";
#endif
videoAd.LoadAd(new AdRequest.Builder().Build(), adUnitID);
pass = pass + 1;
}
void VideoAd()
{
if (videoAd.IsLoaded())
{
videoAd.Show();
}
else
{
//ad not loaded
}
}
//Ad Events
public void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
if (pass < 2)
{
LoadVideoAd();
}
else
{
StartCoroutine(adFailCoro());
}
}
public void HandleOnAdOpening(object ssender, EventArgs args)
{
adPlaying = true;
}
public void HandleOnAdClosed(object sender, EventArgs args)
{
adPlaying = false;
watched = true;
if (watched == true)
{
control controlScript = GameObject.FindGameObjectWithTag("Control").GetComponent<control>();
lifeAdUI.enabled = false;
StartCoroutine(controlScript.ExtraLife());
}
}
public void HandleOnAdReward(object sender, EventArgs args)
{
watched = true;
}
public void HandleOnAdLeavingApplication(object sender, EventArgs args)
{
}
public void HandleOnAdLoaded(object sender, EventArgs args)
{
}
public void HandleOnAdStarted(object sender, EventArgs args)
{
}
}
If you called VideoAd to show your video Ad but due to some unforeseen reason your video is not loaded yet, or having loading failure, so request to load your Ad Again.
void VideoAd()
{
if (videoAd.IsLoaded())
{
videoAd.Show();
}
else
{
LoadVideoAd();
}
}
Request to load new Video Ad when your Ad is closed by user.
public void HandleOnAdClosed(object sender, EventArgs args)
{
adPlaying = false;
watched = true;
if (watched == true) //what is the need of this condition, it always true
{
control controlScript = GameObject.FindGameObjectWithTag("Control").GetComponent<control>();
lifeAdUI.enabled = false;
StartCoroutine(controlScript.ExtraLife());
LoadVideoAd();
}
}
Init Admob Unity Plugin
using admob;
Admob.Instance().initAdmob("admob banner id", "admob interstitial id");//admob id with format ca-app-pub-279xxxxxxxx/xxxxxxxx
//Admob.Instance().initAdmob("ca-app-pub-3940256099942544/2934735716", "ca-app-pub-3940256099942544/4411468910");
Here is the minimal code to create an admob video.
Admob.Instance().loadRewardedVideo("ca-app-pub-3940256099942544/1712485313");
Video need to be explicitly shown at an appropriate stopping point in your app, check that the video is ready before showing it:
if (Admob.Instance().isRewardedVideoReady()) {
Admob.Instance().showRewardedVideo();
}
handle reward
Admob.Instance().videoEventHandler += onVideoEvent;
void onVideoEvent(string eventName, string msg)
{
Debug.Log("handler onAdmobEvent---" + eventName + " " + msg);
if (eventName == AdmobEvent.onRewarded)
{
//msg is the reward count.you can handle it now
}
}
ref admob plugin
Related
I am using admob for ads. Ads working very well on the Editor but on the phone it doesn't. I have a button in the game that show rewarded ads then load next level. And I am showing interstitial ads at end of the level then load next level. But after loading next level game crashes. I am trying to fix it for days but it keeps happening. I am adding my ad manager script. (unit ids not empty of course)
using System.Collections;
using UnityEngine;
using GoogleMobileAds.Api;
using System;
public class AdManager : MonoBehaviour
{
public static AdManager instance;
private BannerView bannerView;
private RewardedAd rewardedAd;
private InterstitialAd interstitialAd;
#if UNITY_ANDROID
string bannerAdUnitId = " ";
string rewardedAdUnitId = " ";
string interstitialAdUnitId = " ";
#else
string bannerAdUnitId = "unexpected_platform";
string rewardedAdUnitId = "unexpected_platform";
string interstitialAdUnitId = "unexpected_platform";
#endif
void Awake()
{
if(instance != null && instance != this){
Destroy(this.gameObject);
}
else{
instance = this;
DontDestroyOnLoad(this.gameObject);
}
}
private void Start() {
MobileAds.Initialize(initStatus => { });
RequestInterstitialAd();
RequestBannerAd();
RequestRewardedAd();
}
//BANNER
public void RequestBannerAd(){
if (bannerView != null)
bannerView.Destroy();
else{
bannerView = new BannerView(bannerAdUnitId, AdSize.Banner, AdPosition.Bottom);
AdRequest request = new AdRequest.Builder().Build();
bannerView.LoadAd(request);
}
}
//REWARDED
public void RequestRewardedAd(){
if(rewardedAd != null)
rewardedAd.Destroy();
rewardedAd = new RewardedAd(rewardedAdUnitId);
// Called when an ad request failed to show.
rewardedAd.OnAdFailedToShow += HandleRewardedAdFailedToShow;
// Called when the ad is closed.
rewardedAd.OnAdClosed += HandleRewardedAdClosed;
AdRequest request = new AdRequest.Builder().Build();
rewardedAd.LoadAd(request);
}
public void ShowRewardedAd(){
if (rewardedAd.IsLoaded()) {
rewardedAd.Show();
}
else{
StartCoroutine(RewardedNotLoadedFunctionCall());
}
}
IEnumerator RewardedNotLoadedFunctionCall(){
FindObjectOfType<GameManagement>().RewardedAdNotLoaded();
yield return null;
}
public void HandleRewardedAdClosed(object sender, EventArgs args)
{
RequestRewardedAd();
StartCoroutine(AdClosedFunctionCall());
}
IEnumerator AdClosedFunctionCall(){
FindObjectOfType<GameManagement>().AdClosed();
yield return null;
}
public void HandleRewardedAdFailedToShow(object sender, AdErrorEventArgs args)
{
StartCoroutine(RewardedNotLoadedFunctionCall());
}
//interstitial
private void RequestInterstitialAd(){
if(interstitialAd != null)
interstitialAd.Destroy();
interstitialAd = new InterstitialAd(interstitialAdUnitId);
interstitialAd.OnAdClosed += HandleOnAdClosed;
AdRequest request = new AdRequest.Builder().Build();
interstitialAd.LoadAd(request);
}
public void ShowInterstitialAd(){
if (interstitialAd.IsLoaded()) {
interstitialAd.Show();
}
else{
StartCoroutine(AdClosedFunctionCall());
}
}
public void HandleOnAdClosed(object sender, EventArgs args)
{
RequestInterstitialAd();
StartCoroutine(AdClosedFunctionCall());
}
}
logcat
Admob Ad does not run on the same thread as Unity's main thread.
rewardedAd.OnAdClosed += HandleRewardedAdClosed;
Calling Unity's function from Admob's thread will lead to unexpected error.
First, add UnityMainThreadDispatcher to your project. All functions called by Admob's callback need be queued by UnityMainThreadDispatcher to main thread:
public void HandleRewardedAdClosed(object sender, EventArgs args)
{
UnityMainThreadDispatcher.Instance().Enqueue(()=>{
RequestRewardedAd();
StartCoroutine(AdClosedFunctionCall());
});
}
Secondly, you should not use FindObjectOfType(). This is an expensive operation and you might run into NullReferenceException if it fails to find the GameManagement object. And since this exception did not happen on Unity's main thread, the logcat message was cryptic.
You should use Singleton or Observer pattern instead.
Thirdly, you're giving reward to user even if they skip the reward ad. Use rewardedAd.OnUserEarnedReward to make sure user have earned the reward ad.
I want to implement IAP in my android game.
This is my code, it is from the official unity website:
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Purchasing;
using UnityEngine.UI;
public class Purchaser : MonoBehaviour, IStoreListener {
private static IStoreController m_StoreController; // The Unity Purchasing system.
private static IExtensionProvider m_StoreExtensionProvider; // The store-specific Purchasing subsystems.
public Text text;
public static string kProductIDConsumable = "pile_shadycoin";
void Start() {
if (m_StoreController == null) {
InitializePurchasing();
}
}
public void InitializePurchasing() {
if (IsInitialized()) {
return;
}
var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
builder.AddProduct(kProductIDConsumable, ProductType.Consumable);
UnityPurchasing.Initialize(this, builder);
}
private bool IsInitialized() {
return m_StoreController != null && m_StoreExtensionProvider != null;
}
public void BuyConsumable() {
BuyProductID(kProductIDConsumable);
}
void BuyProductID(string productId) {
if (IsInitialized()) {
Product product = m_StoreController.products.WithID(productId);
if (product != null && product.availableToPurchase) {
text.text = "Purchasing product asychronously: '{0}'";
m_StoreController.InitiatePurchase(product);
} else {
text.text = "BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase";
}
} else {
text.text = "BuyProductID FAIL. Not initialized.";
}
}
public void OnInitialized(IStoreController controller, IExtensionProvider extensions) {
text.text = "OnInitialized: PASS";
m_StoreController = controller;
m_StoreExtensionProvider = extensions;
}
public void OnInitializeFailed(InitializationFailureReason error) {
text.text = "OnInitializeFailed InitializationFailureReason:" + error;
}
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args) {
if (String.Equals(args.purchasedProduct.definition.id, kProductIDConsumable, StringComparison.Ordinal)) {
text.text = "ProcessPurchase: PASS. Product: '{0}'";
} else {
text.text = "ProcessPurchase: FAIL. Unrecognized product: '{0}'";
}
return PurchaseProcessingResult.Complete;
}
public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason) {
text.text = failureReason + "";
}
}
I am using the consumable item pile_shadycoin.
In the picture you can see the id and that it's active (it's german)
Picture of Google Play
If I build my project and put it on my smartphone and press the button, which is linked to BuyConsumable() it opens the menu and says:
Fehler Der angeforderte Artikel kann nicht gekauft werden
In English:
Error The requested item cannot be purchased
I found my error. I didn't released the build on alpha or beta.
I pulled the APK directly to my phone.
Following on through the Google AdMob read on implementation for the varying ads:
https://developers.google.com/admob/unity/banner
https://developers.google.com/admob/unity/interstitial
Right now I have a C# Script which implements these ads and I go on to create a game object inside my inspector which has this script.
I believe that this is enough information for me to get a straight forward answer hopefully without any code required and a very general one.
I would like to know whether this object should be initialized only once, ideally in the Main Menu scene and be recycled through the other scenes to manage the reference to these ads.
OR
Delete the existing game object which manages those ads to then have the following scene instantiate a new one, potentially showing a different advert to the one previous.
EDIT:
AdManager Script:
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using GoogleMobileAds.Api;
public class AdManager : MonoBehaviour
{
public static AdManager instance;
//Test id: ca-app-pub-3940256099942544~3347511713
private string APP_ID = "An id";
private BannerView bannerAD;
private InterstitialAd interstitialAD;
private void Awake()
{
if (instance != null)
{
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
}
}
// Start is called before the first frame update
void Start()
{
//FOR PUBLISHING ONLY
//MobileAds.Initialize(APP_ID);
RequestBannerAD();
RequestInterstitialAD();
}
private void RequestBannerAD()
{
string banner_ID = "ca-app-pub-3940256099942544/6300978111";
bannerAD = new BannerView(banner_ID, AdSize.Banner, AdPosition.Bottom);
// Called when an ad request has successfully loaded.
bannerAD.OnAdLoaded += HandleOnAdLoaded;
// Called when an ad request failed to load.
bannerAD.OnAdFailedToLoad += HandleOnAdFailedToLoad;
// Called when an ad is clicked.
bannerAD.OnAdOpening += HandleOnAdOpened;
// Called when the user returned from the app after an ad click.
bannerAD.OnAdClosed += HandleOnAdClosed;
// Called when the ad click caused the user to leave the application.
bannerAD.OnAdLeavingApplication += HandleOnAdLeavingApplication;
//FOR PRODUCTION
//AdRequest adRequest = new AdRequest.Builder().Build();
//FOR TESTING
AdRequest adRequest = new AdRequest.Builder().AddTestDevice("2077ef9a63d2b398840261c8221a0c9b").Build();
bannerAD.LoadAd(adRequest);
void HandleOnAdLoaded(object sender, EventArgs args)
{
Display_Banner();
}
void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
RequestBannerAD();
}
void HandleOnAdOpened(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdOpened event received");
}
void HandleOnAdClosed(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdClosed event received");
}
void HandleOnAdLeavingApplication(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdLeavingApplication event received");
}
}
public void Display_Banner()
{
bannerAD.Show();
}
public void DestroyBanner()
{
bannerAD.Destroy();
}
private void RequestInterstitialAD()
{
string interstitial_ID = "ca-app-pub-3940256099942544/1033173712";
interstitialAD = new InterstitialAd(interstitial_ID);
// Called when an ad request has successfully loaded.
interstitialAD.OnAdLoaded += HandleOnAdLoaded;
// Called when an ad request failed to load.
interstitialAD.OnAdFailedToLoad += HandleOnAdFailedToLoad;
// Called when an ad is clicked.
interstitialAD.OnAdOpening += HandleOnAdOpened;
// Called when the user returned from the app after an ad click.
interstitialAD.OnAdClosed += HandleOnAdClosed;
// Called when the ad click caused the user to leave the application.
interstitialAD.OnAdLeavingApplication += HandleOnAdLeavingApplication;
//FOR PRODUCTION
//AdRequest adRequest = new AdRequest.Builder().Build();
//FOR TESTING
AdRequest adRequest = new AdRequest.Builder().AddTestDevice("2077ef9a63d2b398840261c8221a0c9b").Build();
interstitialAD.LoadAd(adRequest);
void HandleOnAdLoaded(object sender, EventArgs args)
{
}
void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
}
void HandleOnAdOpened(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdOpened event received");
}
void HandleOnAdClosed(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdClosed event received");
}
void HandleOnAdLeavingApplication(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdLeavingApplication event received");
}
}
public void Display_Interstitial()
{
if (interstitialAD.IsLoaded())
{
interstitialAD.Show();
}
}
public void DestroyInterstitial()
{
interstitialAD.Destroy();
}
}
MenuLoader Script (fragment to interstitial call attached to a UI Button):
public void LoadGameOver()
{
StartCoroutine(WaitAndLoad_GameOver());
}
private IEnumerator WaitAndLoad_GameOver()
{
yield return new WaitForSeconds(gameOver_loadDelay);
FindObjectOfType<AdManager>().Display_Interstitial();
SceneManager.LoadScene("Game Over");
}
EDIT 2 (In response to Eliasar):
06-20 22:07:13.988 6492 6518 E Unity : NullReferenceException: Object reference not set to an instance of an object
06-20 22:07:13.988 6492 6518 E Unity : at AdManager.Display_Banner () [0x00000] in <0b5b8f6032c04370a5fa0fecd73ecd6b>:0
06-20 22:07:13.988 6492 6518 E Unity : at MenuLoader+<WaitAndLoad_Game>d__6.MoveNext () [0x00084] in <0b5b8f6032c04370a5fa0fecd73ecd6b>:0
06-20 22:07:13.988 6492 6518 E Unity : at UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) [0x00027] in <1f017b19aaf9475abf1041405dbaf390>:0
06-20 22:07:13.988 6492 6518 E Unity :
AdManager:
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using GoogleMobileAds.Api;
public static class AdManager
{
//public static AdManager instance;
//Test id: ca-app-pub-3940256099942544~3347511713
private static string APP_ID = "An id";
private static BannerView bannerAD;
private static InterstitialAd interstitialAD;
//private void Awake()
//{
// if (instance != null)
// {
// Destroy(gameObject);
// }
// else
// {
// instance = this;
// DontDestroyOnLoad(gameObject);
// }
//}
// Start is called before the first frame update
//void Start()
//{
// //FOR PUBLISHING ONLY
// //MobileAds.Initialize(APP_ID);
// RequestBannerAD();
// RequestInterstitialAD();
//}
private static void RequestBannerAD()
{
string banner_ID = "ca-app-pub-3940256099942544/6300978111";
bannerAD = new BannerView(banner_ID, AdSize.Banner, AdPosition.Bottom);
// Called when an ad request has successfully loaded.
bannerAD.OnAdLoaded += HandleOnAdLoaded;
// Called when an ad request failed to load.
bannerAD.OnAdFailedToLoad += HandleOnAdFailedToLoad;
// Called when an ad is clicked.
bannerAD.OnAdOpening += HandleOnAdOpened;
// Called when the user returned from the app after an ad click.
bannerAD.OnAdClosed += HandleOnAdClosed;
// Called when the ad click caused the user to leave the application.
bannerAD.OnAdLeavingApplication += HandleOnAdLeavingApplication;
//FOR PRODUCTION
//AdRequest adRequest = new AdRequest.Builder().Build();
//FOR TESTING
AdRequest adRequest = new AdRequest.Builder().AddTestDevice("2077ef9a63d2b398840261c8221a0c9b").Build();
bannerAD.LoadAd(adRequest);
void HandleOnAdLoaded(object sender, EventArgs args)
{
Display_Banner();
}
void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
RequestBannerAD();
}
void HandleOnAdOpened(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdOpened event received");
}
void HandleOnAdClosed(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdClosed event received");
}
void HandleOnAdLeavingApplication(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdLeavingApplication event received");
}
}
public static void Display_Banner()
{
bannerAD.Show();
}
public static void DestroyBanner()
{
bannerAD.Destroy();
}
private static void RequestInterstitialAD()
{
string interstitial_ID = "ca-app-pub-3940256099942544/1033173712";
interstitialAD = new InterstitialAd(interstitial_ID);
// Called when an ad request has successfully loaded.
interstitialAD.OnAdLoaded += HandleOnAdLoaded;
// Called when an ad request failed to load.
interstitialAD.OnAdFailedToLoad += HandleOnAdFailedToLoad;
// Called when an ad is clicked.
interstitialAD.OnAdOpening += HandleOnAdOpened;
// Called when the user returned from the app after an ad click.
interstitialAD.OnAdClosed += HandleOnAdClosed;
// Called when the ad click caused the user to leave the application.
interstitialAD.OnAdLeavingApplication += HandleOnAdLeavingApplication;
//FOR PRODUCTION
//AdRequest adRequest = new AdRequest.Builder().Build();
//FOR TESTING
AdRequest adRequest = new AdRequest.Builder().AddTestDevice("2077ef9a63d2b398840261c8221a0c9b").Build();
interstitialAD.LoadAd(adRequest);
void HandleOnAdLoaded(object sender, EventArgs args)
{
}
void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
}
void HandleOnAdOpened(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdOpened event received");
}
void HandleOnAdClosed(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdClosed event received");
}
void HandleOnAdLeavingApplication(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdLeavingApplication event received");
}
}
public static void Display_Interstitial()
{
if (interstitialAD.IsLoaded())
{
interstitialAD.Show();
}
}
public static void DestroyInterstitial()
{
interstitialAD.Destroy();
}
}
MenuLoader (fragment edit):
public void LoadGameOver()
{
StartCoroutine(WaitAndLoad_GameOver());
}
private IEnumerator WaitAndLoad_GameOver()
{
yield return new WaitForSeconds(gameOver_loadDelay);
AdManager.Display_Interstitial();
//FindObjectOfType<AdManager>().Display_Interstitial();
SceneManager.LoadScene("Game Over");
AdManager.Display_Banner();
}
in my game when character die i want to show banner and hide it when player press restart button. Its work fine but after first reset when i want to show banner i get error
NullReferenceException: Object reference not set to an instance of an object
GoogleMobileAdsDemoScript.showBanner ()
so should i request banner after every game restart? it wont be too laggy?
i tried also to attach DontDestroyOnLoad (this); to object which has my ad scripts but it didnt work.
My restart button: Application.LoadLevel (Application.loadedLevel);
AD Script `
private BannerView bannerView;
private InterstitialAd interstitial;
private static string outputMessage = "";
public static string OutputMessage
{
set { outputMessage = value; }
}
private void RequestBanner()
{
#if UNITY_EDITOR
string adUnitId = "unused";
#elif UNITY_ANDROID
string adUnitId = "myai";
#elif UNITY_IPHONE
string adUnitId = "INSERT_IOS_BANNER_AD_UNIT_ID_HERE";
#else
string adUnitId = "unexpected_platform";
#endif
// Create a 320x50 banner at the top of the screen.
bannerView = new BannerView(adUnitId, AdSize.SmartBanner, AdPosition.Top);
// Register for ad events.
bannerView.AdLoaded += HandleAdLoaded;
bannerView.AdFailedToLoad += HandleAdFailedToLoad;
bannerView.AdOpened += HandleAdOpened;
bannerView.AdClosing += HandleAdClosing;
bannerView.AdClosed += HandleAdClosed;
bannerView.AdLeftApplication += HandleAdLeftApplication;
// Load a banner ad.
bannerView.LoadAd(createAdRequest());
}
private void RequestInterstitial()
{
#if UNITY_EDITOR
string adUnitId = "unused";
#elif UNITY_ANDROID
string adUnitId = "INSERT_ANDROID_INTERSTITIAL_AD_UNIT_ID_HERE";
#elif UNITY_IPHONE
string adUnitId = "INSERT_IOS_INTERSTITIAL_AD_UNIT_ID_HERE";
#else
string adUnitId = "unexpected_platform";
#endif
// Create an interstitial.
interstitial = new InterstitialAd(adUnitId);
// Register for ad events.
interstitial.AdLoaded += HandleInterstitialLoaded;
interstitial.AdFailedToLoad += HandleInterstitialFailedToLoad;
interstitial.AdOpened += HandleInterstitialOpened;
interstitial.AdClosing += HandleInterstitialClosing;
interstitial.AdClosed += HandleInterstitialClosed;
interstitial.AdLeftApplication += HandleInterstitialLeftApplication;
GoogleMobileAdsDemoHandler handler = new GoogleMobileAdsDemoHandler();
interstitial.SetInAppPurchaseHandler(handler);
// Load an interstitial ad.
interstitial.LoadAd(createAdRequest());
}
// Returns an ad request with custom ad targeting.
private AdRequest createAdRequest()
{
return new AdRequest.Builder()
.AddTestDevice(AdRequest.TestDeviceSimulator)
.AddTestDevice("0123456789ABCDEF0123456789ABCDEF")
.AddKeyword("game")
.SetGender(Gender.Male)
.SetBirthday(new DateTime(1985, 1, 1))
.TagForChildDirectedTreatment(false)
.AddExtra("color_bg", "9B30FF")
.Build();
}
private void ShowInterstitial()
{
if (interstitial.IsLoaded())
{
interstitial.Show();
}
else
{
print("Interstitial is not ready yet.");
}
}
#region Banner callback handlers
public void HandleAdLoaded(object sender, EventArgs args)
{
print("HandleAdLoaded event received.");
}
public void HandleAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
print("HandleFailedToReceiveAd event received with message: " + args.Message);
}
public void HandleAdOpened(object sender, EventArgs args)
{
print("HandleAdOpened event received");
}
void HandleAdClosing(object sender, EventArgs args)
{
print("HandleAdClosing event received");
}
public void HandleAdClosed(object sender, EventArgs args)
{
print("HandleAdClosed event received");
}
public void HandleAdLeftApplication(object sender, EventArgs args)
{
print("HandleAdLeftApplication event received");
}
#endregion
#region Interstitial callback handlers
public void HandleInterstitialLoaded(object sender, EventArgs args)
{
print("HandleInterstitialLoaded event received.");
}
public void HandleInterstitialFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
print("HandleInterstitialFailedToLoad event received with message: " + args.Message);
}
public void HandleInterstitialOpened(object sender, EventArgs args)
{
print("HandleInterstitialOpened event received");
}
void HandleInterstitialClosing(object sender, EventArgs args)
{
print("HandleInterstitialClosing event received");
}
public void HandleInterstitialClosed(object sender, EventArgs args)
{
print("HandleInterstitialClosed event received");
}
public void HandleInterstitialLeftApplication(object sender, EventArgs args)
{
print("HandleInterstitialLeftApplication event received");
}
#endregion
`
What should i do?
I recommend you use a plugin of Appodeal.
I've been trying to integrate facebook into my project and I've successfully managed to do just that with the help of some online tutorials however I do have one persisting problem...
The code is set to pause the game using
Time.timescale = 0; when a facebook window is up and to resume play using Time.timescale = 1; when it's not
but that just doesn't happen, and the function that pauses the game never gets called...
Here's the code :
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class FBHolder : MonoBehaviour {
public GameObject UIFBIsLoggedIn;
public GameObject UIFBNotLoggedIn;
public GameObject UIFBAvatar;
public GameObject UIFBUserName;
public GameObject ScoreEntryPanel;
public GameObject ScoreScrollList;
private List<object> scoreslist = null;
private Dictionary<string, string> profile = null;
void Awake()
{
FB.Init (SetInit, onHideUnity);
}
private void SetInit()
{
Debug.Log ("FB Init Done");
if(FB.IsLoggedIn)
{
Debug.Log ("FB Logged In");
managefbmenus(true);
}
else
{
managefbmenus(false);
}
}
private void onHideUnity(bool isGameShown)
{
if(!isGameShown)
{
Debug.Log ("Pause Game");
Time.timeScale = 0;
}
else
{
Time.timeScale = 1;
}
}
public void FBLogin()
{
FB.Login ("email,publish_actions", Authcallback);
}
void Authcallback(FBResult result)
{
if(FB.IsLoggedIn)
{
Debug.Log ("FB Login Worked");
managefbmenus(true);
}
else
{
Debug.Log ("FB Login Failed");
managefbmenus(false);
}
}
void managefbmenus(bool isLoggedIn)
{
if(isLoggedIn)
{
UIFBIsLoggedIn.SetActive(true);
UIFBNotLoggedIn.SetActive(false);
SetScore();
//Get profile picture
FB.API(Util.GetPictureURL("me", 128, 128), Facebook.HttpMethod.GET, DealWithProfilePicture);
FB.API("/me?fields=id,first_name", Facebook.HttpMethod.GET,DealwithUserName);
//Get username
}
if(!isLoggedIn)
{
UIFBIsLoggedIn.SetActive(false);
UIFBNotLoggedIn.SetActive(true);
}
}
void DealWithProfilePicture(FBResult result)
{
if(result.Error != null)
{
Debug.Log ("Problem getting profile picture");
FB.API(Util.GetPictureURL("me", 128, 128), Facebook.HttpMethod.GET, DealWithProfilePicture);
return;
}
Image UserAvatar = UIFBAvatar.GetComponent<Image> ();
UserAvatar.sprite = Sprite.Create (result.Texture, new Rect(0, 0, 128, 128), new Vector2(0, 0));
}
void DealwithUserName(FBResult result)
{
if(result.Error != null)
{
Debug.Log ("Problem getting username");
FB.API("/me?fields=id,first_name", Facebook.HttpMethod.GET,DealwithUserName);
return;
}
profile = Util.DeserializeJSONProfile(result.Text);
Text UserMsg = UIFBUserName.GetComponent<Text>();
UserMsg.text = "Hello, " + profile ["first_name"];
}
Any ideas on what could be causing this issue?
BTW: I'm using unity 5.
I guess you don't need to pause your game while Facebook UI is displayed. you can just call it as:
FB.Init(SetInit);