Admob Interstitial ad not showing up at all - c#

I basically copy-pasted and mildly modified the demo project ads setup by the official branch of this Google Mobile Ads and my banner ads show up all right, but no interstitial ads show up - no matter what.
Here's what I did, using my AdManager static class:
This InitializeAds() is called right after starting the game:
public static void InitializeAds()
{
MobileAds.Initialize(appID);
}
And of course, every level where there is an ad, has the following GetSomeAdRequests() inside their Start() method.
public static void GetSomeAdRequests()
{
AdRequestBANNER = CreateAdRequest();
AdRequestINTERST = CreateAdRequest();
}
public static AdRequest CreateAdRequest()
{
AdRequest request = new AdRequest.Builder().Build();
return request;
}
Needless to say I use the tester video and banner IDs provided by Google.
Next, my RequestInterstitial:
public static void RequestInterstitial()
{
// These ad units are configured to always serve test ads.
#if UNITY_EDITOR
string adUnitId = "unused";
#elif UNITY_ANDROID
string adUnitId = videoID;
#else
string adUnitId = "unexpected_platform";
#endif
// Clean up interstitial ad before creating a new one.
if (interstitial != null)
{
interstitial.Destroy();
}
// Create an interstitial.
interstitial = new InterstitialAd(adUnitId);
// Register for ad events.
interstitial.OnAdLoaded += HandleInterstitialLoaded;
interstitial.OnAdFailedToLoad += HandleInterstitialFailedToLoad;
interstitial.OnAdOpening += HandleInterstitialOpened;
interstitial.OnAdClosed += HandleInterstitialClosed;
interstitial.OnAdLeavingApplication += HandleInterstitialLeftApplication;
// Load an interstitial ad.
interstitial.LoadAd(AdRequestINTERST);
if (interstitial.IsLoaded())
{
interstitial.Show();
}
}
And finally AdRequestINTERST is:
private static AdRequest adRequestINTERST;
public static AdRequest AdRequestINTERST
{
get
{
if (adRequestINTERST == null)
{
adRequestINTERST = CreateAdRequest();
}
return adRequestINTERST;
}
set
{
adRequestINTERST = value;
}
}
implemented this way to make sure the request is never null.
Now, I do give a lot of time for the vid to initialize, as it should load upon leve start, but it still doesn't do anything. No error, no freeze.
In the editor play, I tested it using Debug.Log and it reaches the code to actually call the ad. It just doesn't show up, whereas the banner ad works fine.
Any ideas?

I think I got it now.
So the way I could make this work is this:
I load the ads when I initialize the scene, or, to be exact, start the request right beforehand. and hide them after the load.
And when I want the ads to show up, I just call the Show() method and boom, they are there.
My issue what that the internet speed ain't the best around here and I requested and wanted to show right after the request which won't happen.

Just give proper time to load the ad, like for testing use the handler post delayed of 10 second to give time to load ad and after 10seconds ad will load.
To check you can simply use my same code in any activity
var adRequest = AdRequest.Builder().build()
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest, object : InterstitialAdLoadCallback() {
override fun onAdFailedToLoad(adError: LoadAdError) {
Log.d(TAG, adError?.message)
mInterstitialAd = null
}
override fun onAdLoaded(interstitialAd: InterstitialAd) {
Log.d(TAG, "Ad was loaded.")
mInterstitialAd = interstitialAd
}
})
Handler().postDelayed({
if (mInterstitialAd != null) {
println("executed")
mInterstitialAd?.show(this)
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.")
}
}, 10000)

Related

Migrating to UnityAds 4.3.0 ShowOptions Problem

I'am in the process of migrating my game to the new UnityAds 4.3.0.
I am unable to comprehend how to migrate to the new unity listeners and how to use the old code.
I have added the listners
public class UnityAdsManager : MonoBehaviour, IUnityAdsInitializationListener, IUnityAdsLoadListener, IUnityAdsShowListener
My old code
button_video.GetComponent<Button>().onClick.AddListener(delegate
{
playSound(buttonSound);
//RewarderAd
if (Advertisement.IsReady("rewardedVideo"))
{
UnityEngine.Debug.Log("Advertisement.IsReady2");
ShowOptions showOptions = new ShowOptions
{
resultCallback = delegate(ShowResult result)
{
if (result == ShowResult.Finished && isVideo)
{
SecurityPlayerPrefs.SetInt("Credit", credit);
}
}
};
Advertisement.Show(_adUnitId, this);
}
Advertisement.Show(_adUnitId, this);
Debug.Log("Ad Showing: " + _adUnitId);
});
isFreeView = true;
}
I understand that the oncompletion code will get the rewards done.
// Implement the Show Listener's OnUnityAdsShowComplete callback method to determine if the user gets a reward:
public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState)
{
if (adUnitId.Equals(_adUnitId) && showCompletionState.Equals(UnityAdsShowCompletionState.COMPLETED))
{
Debug.Log("Unity Ads Rewarded Ad Completed");
// Grant a reward.
// Load another ad:
Advertisement.Load(_adUnitId, this);
}
}
is there a possibility to use the old code "ShowOption" and reward the user.
Or am I going about this the wrong way?

SceneManager.LoadScene doesn't work on development mobile build

I'm trying to build a Unity game on android/iOS by checking the development build option (so that I can use the profiler for debugging), but the SceneManager.LoadScene function doesn't work. I tried the scene name and index as the function parameters, but both didn't work.
It's important to note that the game works perfectly fine if I uncheck the development build option. I'm currently using Unity 2019.3.5.f1.
Edit:
I noticed that the scene loads without any problems when I run SceneManager.LoadScene from the Start() function. However, in most parts of my code, I run SceneManager.LoadScene from inside other functions, such as event handlers.
Here are a few code examples:
I run this function in Awake(). It reaches SceneManager.LoadScene("Credentials"); then stops:
private void ConfirmGooglePlayerServicesRequirements()
{
Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task => {
var dependencyStatus = task.Result;
if (dependencyStatus == Firebase.DependencyStatus.Available)
{
// Create and hold a reference to your FirebaseApp,
// where app is a Firebase.FirebaseApp property of your application class.
app = Firebase.FirebaseApp.DefaultInstance;
InitializeFirebase();
if (!signedIn)
SceneManager.LoadScene("Credentials");
}
else
{
Debug.LogError(System.String.Format(
"Could not resolve all Firebase dependencies: {0}", dependencyStatus));
// Firebase Unity SDK is not safe to use here.
}
});
}
This is a Firebase function which is called whenever a user signs in/out. It invokes an event called signedInEvent, which is handled by a function in another script that runs SceneManager.LoadScene.
void AuthStateChanged(object sender, System.EventArgs eventArgs)
{
if (auth.CurrentUser != user)
{
signedIn = user != auth.CurrentUser && auth.CurrentUser != null;
if (!signedIn && user != null)
{
Debug.Log("Signed out " + user.UserId);
}
user = auth.CurrentUser;
if (signedIn)
{
Debug.Log("Signed in " + user.UserId);
displayName = user.DisplayName ?? "";
emailAddress = user.Email ?? "";
userId = user.UserId ?? "";
signedInEvent.Invoke(displayName, emailAddress, userId);
}
}
}
Notes:
Scenes/FirstScene is enabled. It was disabled when I took the screenshot above because I was doing some tests.
I got this error using adb (android debug bridge) a while ago when I ran the game in development mode. It might be related to this issue: FindGameObjectWithTag can only be called from the main thread
Thanks!
FindGameObjectWithTag can only be called from the main thread
This is indeed related! Now that you posted your code:
ContinueWith might get called on a background thread. Most of the Unity API may only be called from the main thread otherwise it might either show an error such as the one you mentioned or sometimes it just fails silently.
In general this is often solved by something like e.g. UnityMainThreadDispatcher.
However, specifically for Firebase there already exists an extension called ContinueWithOnMainThread in the Firebase.Extensions namespace which makes sure the callback code is actually executed in the main thread where the Unity API works.
Extension methods for System.Threading.Tasks.Task and System.Threading.Tasks.Task<T> that allow the continuation function to be executed on the main thread in Unity.
using Firebase.Extensions;
private void ConfirmGooglePlayerServicesRequirements()
{
Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => {
var dependencyStatus = task.Result;
if (dependencyStatus == Firebase.DependencyStatus.Available)
{
// Create and hold a reference to your FirebaseApp,
// where app is a Firebase.FirebaseApp property of your application class.
app = Firebase.FirebaseApp.DefaultInstance;
InitializeFirebase();
if (!signedIn)
{
SceneManager.LoadScene("Credentials");
}
}
else
{
Debug.LogError($"Could not resolve all Firebase dependencies: {dependencyStatus}", this);
// Firebase Unity SDK is not safe to use here.
}
});
}

Windows 10 Iot Core app crashes if I try to open a PWM pin

I want to open a PWM pin to my buzzer. But If I try to call the pwmController.OpenPin(6) method, the app crashes with an System.Runtime.InteropServices.SEHException.
I had already double checked the sample sources like the ms-iot-samples. But I cannot see what my problems are.
An idea was that some permissions are missing, but if I try to add for exmaple <iot:Capability Name="lowLevelDevices" />, I cannot longer build the application.
Source
private PwmPin buzzerPin;
private PwmController pwmController;
public RainbowHAT()
{
// ... do something else
InitAsync();
}
private async void InitAsync()
{
Logger.Log(this, "Init");
// Setup PWM controller.
if (LightningProvider.IsLightningEnabled)
{
LowLevelDevicesController.DefaultProvider = LightningProvider.GetAggregateProvider();
}
var pwmControllers = await PwmController.GetControllersAsync(LightningPwmProvider.GetPwmProvider());
if (pwmControllers == null || pwmControllers.Count < 2)
{
throw new OperationCanceledException("Operation canceled due missing GPIO controller");
}
pwmController = pwmControllers[1];
pwmController.SetDesiredFrequency(50);
// Setup buzzer
buzzerPin = pwmController.OpenPin(13); <-- CRASH
buzzerPin.SetActiveDutyCyclePercentage(0.05);
buzzerPin.Start();
}
I also tried the following tip to reduce the min required Windows version, but this does not help, too.
PWM Controller needs Lightning support. So you need to set the controller driver as Direct Memory Mapped Driver. Here is a sample about PWM on Raspberry Pi.
You also need to modify the code as following:
private async void InitAsync()
{
Logger.Log(this, "Init");
// Setup PWM controller.
if (LightningProvider.IsLightningEnabled)
{
var pwmControllers = await PwmController.GetControllersAsync(LightningPwmProvider.GetPwmProvider());
if (pwmControllers == null || pwmControllers.Count < 2)
{
throw new OperationCanceledException("Operation canceled due missing GPIO controller");
}
pwmController = pwmControllers[1];
pwmController.SetDesiredFrequency(50);
// Setup buzzer
buzzerPin = pwmController.OpenPin(13);
buzzerPin.SetActiveDutyCyclePercentage(0.05);
buzzerPin.Start();
}
}

Anyone know how to use the FBNativeAdBridgeCallback function in audience network unity

Can anyone please tell me how to use the FBNativeAdBridgeCallback function? i basically want to know when the images are finished loaded so that i can display them. . else i have a native banner flying around with empty values until Facebook has finished loading them. and it looks really ugly if each image/text loads in one at a time.
Its just the basic native ads sample script, i tried using IResult like one does with the login, but that makes it red. there is no documentation on this on the internet, not even on the Facebook developer site, i can't find the api at all.
Can anyone please explain to me how to use it in the script provided below?
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using AudienceNetwork;
[RequireComponent (typeof(CanvasRenderer))]
[RequireComponent (typeof(RectTransform))]
public class NativeAdTest : MonoBehaviour
{
private NativeAd nativeAd;
// UI elements in scene
[Header("Text:")]
public Text
title;
public Text socialContext;
[Header("Images:")]
public Image
coverImage;
public Image iconImage;
[Header("Buttons:")]
public Text
callToAction;
public Button callToActionButton;
public GameObject hide;
void Awake ()
{
// Create a native ad request with a unique placement ID (generate your own on the Facebook app settings).
// Use different ID for each ad placement in your app.
NativeAd nativeAd = new AudienceNetwork.NativeAd ("your placement id");
this.nativeAd = nativeAd;
// Wire up GameObject with the native ad; the specified buttons will be clickable.
nativeAd.RegisterGameObjectForImpression (gameObject, new Button[] { callToActionButton });
// Set delegates to get notified on changes or when the user interacts with the ad.
nativeAd.NativeAdDidLoad = (delegate() {
Debug.Log ("Native ad loaded.");
Debug.Log ("Loading images...");
// Use helper methods to load images from native ad URLs
StartCoroutine (nativeAd.LoadIconImage (nativeAd.IconImageURL));
StartCoroutine (nativeAd.LoadCoverImage (nativeAd.CoverImageURL));
Debug.Log ("Images loaded.");
title.text = nativeAd.Title;
socialContext.text = nativeAd.SocialContext;
callToAction.text = nativeAd.CallToAction;
Debug.Log ("Native ad Luke.");
// hide.SetActive(false);
//FBNativeAdBridgeCallback
});
nativeAd.NativeAdDidFailWithError = (delegate(string error) {
Debug.Log ("Native ad failed to load with error: " + error);
});
nativeAd.NativeAdWillLogImpression = (delegate() {
Debug.Log ("Native ad logged impression.");
});
nativeAd.NativeAdDidClick = (delegate() {
Debug.Log ("Native ad clicked.");
});
// Initiate a request to load an ad.
nativeAd.LoadAd ();
//nativeAd.nat
}
void OnGUI ()
{
// Update GUI from native ad
coverImage.sprite = nativeAd.CoverImage;
iconImage.sprite = nativeAd.IconImage;
}
void OnDestroy ()
{
// Dispose of native ad when the scene is destroyed
if (this.nativeAd) {
this.nativeAd.Dispose ();
}
Debug.Log ("NativeAdTest was destroyed!");
}
// void FBNativeAdBridgeCallback(IResult result)
// {
//
// }
}
Thanks in advance!
AdView does not allow you to define a customized listener from FBNativeAdBridgeCallback(). AdView already provided 5 callbacks includes NativeAdDidLoad().
The solution to your question is to hide the ad first, then after you received the NativeAdDidLoad() and finished loading images, bring the ad to front and make it visible. There is no need to create a new FBNativeAdBridgeCallback().

Facebook SDK and threads (WebBrowser control)

This is probably more of a general c# and simple threading question than it is a Facebook SDK question, but I may be wrong. But I could really use some help. I am reusing the sample code that comes with the SDK which includes a FacebookLoginDialog class. I am currently using it like this. In my GetMessages, GetFriendRequests, and other Get* classes, I always try/catch calls like this:
try
{
var result = (IDictionary<string, object>)fb.Get("/me/inbox");
}
catch (FacebookOAuthException e)
{
FacebookSession.Login();
}
Here's my login method in my FacebookSession class
public static void Login()
{
var fbLoginDialog = new FacebookLoginDialog(APP_ID, EXTENDED_PERMISSIONS);
DialogResult dr = fbLoginDialog.ShowDialog();
DisplayAppropriateMessage(fbLoginDialog.FacebookOAuthResult);
}
And here is the constructor in my FacebookLoginDialog class (this is where I have the problem)
public FacebookLoginDialog(string appId, string[] extendedPermissions, bool logout)
{
try
{
var oauth = new FacebookOAuthClient { AppId = appId };
var loginParameters = new Dictionary<string, object>
{
{ "response_type", "token" },
{ "display", "popup" }
};
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
loginParameters["scope"] = scope.ToString();
}
var loginUrl = oauth.GetLoginUrl(loginParameters);
if (logout)
{
var logoutParameters = new Dictionary<string, object>
{
{ "next", loginUrl }
};
System.Uri uri =
new Uri("https://www.facebook.com/logout.php?next=" +
"https://www.facebook.com/connect/login_success.html&access_token=" +
FacebookSession._accessToken);
this.navigateUrl = uri;
}
else
{
this.navigateUrl = loginUrl;
}
InitializeComponent(); // crash here... sometimes
}
catch (Exception e)
{
//Log error message
}
}
Sorry for all the code, but now the problem. This code works fine the first time through. If I go to my facebook applications permissions page in Facebook and remove the app (that is, remove its permissions), while my desktop app here is NOT running, when I do start it up, it sees that it does not have permission and shows the login dialog. I can save the access_key and it will work just fine. But if I go to the facebook apps page and yank the permissions while my desktop app is running, then bad things happen. I get an error message about the activex control cannot be instantiated because the current thread is not in a single-threaded apartment. I have seen many posts here that say all you have to do is put [STAThread] above your main(), and my code has that. I have also tried creating a new thread to call the FacebookLoginDialog, but not only did that not work, but since my code is really not designed to run in multiple threads, that started causing more problems.
Is there a simple solution to all this, or do I need to redesign my code so that it properly runs in multiple threads? Or should I just live with the program crashing in those few instances when someone monkeys with the facebook permissions while my app is running?

Categories