Migrating to UnityAds 4.3.0 ShowOptions Problem - c#

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?

Related

Unity Firebase SignInAnonymously sometimes works and sometimes not

I have an issue with signing in anonymously into my Firebase database for my Unity game. I have a method for signing anonymously into the database and another one that reads the database and prints a json string.
public IEnumerator anonymousSignIn()
{
var register = auth.SignInAnonymouslyAsync();
yield return new WaitUntil(predicate: ()=> register.IsCompleted);
}
public IEnumerator readDatabase()
{
var DBTask = DBreference.Child("users").GetValueAsync();
yield return new WaitUntil(predicate: () => DBTask.IsCompleted);
if (DBTask.Exception != null)
{
Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
}
else if (DBTask.Result.Value == null)
{
Debug.LogWarning("No data found in the database");
}
else
{
DataSnapshot snapshot = DBTask.Result;
string json = snapshot.GetRawJsonValue();
Debug.Log(json);
}
}
I then call these functions via a button in my Unity games using the method:
public void readButton()
{
StartCoroutine(anonymousSign());
StartCoroutine(readDatabase());
}
However, this sometimes works and other times It says permission denied and I don't understand why.
My database rules for reading are: ".read": "auth != null",
I got the same error.
After that, I changed the code
From:
Auth.SignInAnonymouslyAsync().ContinueWith(task => { SignInAnonymously(task, "Guest"); });
To:
Auth.SignInAnonymouslyAsync().ContinueWithOnMainThread(task => { SignInAnonymously(task, "Guest"); });
Don't use Async for Anonymous Sign In, but run on Main Thread.
It worked for me!

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.
}
});
}

Unity Firebase Database working only in editor

I have a piece of code that saves my ussers in my database like so:
public void createAccount()
{
FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://xxx-xxx.firebaseio.com/");
FirebaseApp.DefaultInstance.SetEditorP12FileName("xxx xxx-dd21907c659a.p12");
FirebaseApp.DefaultInstance.SetEditorServiceAccountEmail("xxx#xxx-xxx.iam.gserviceaccount.com");
FirebaseApp.DefaultInstance.SetEditorP12Password("notasecret");
DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;
FirebaseDatabase.DefaultInstance.GetReference("users").Child(username.GetComponent<InputField>().text).Child("likes").GetValueAsync().ContinueWith(task =>
{
if (task.IsFaulted)
{
email.GetComponent<InputField>().textComponent.color = Color.red;
}
else if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
if (snapshot.Value == null)
{
DataBase.userID = username.GetComponent<InputField>().text;
DataBase.email = email.GetComponent<InputField>().text;
DataBase.password = password.GetComponent<InputField>().text;
DataBase.signedIn = true;
reference.Child("users").Child(DataBase.userID).Child("likes").SetValueAsync(DataBase.followers);
reference.Child("users").Child(DataBase.userID).Child("email").SetValueAsync(DataBase.email);
reference.Child("users").Child(DataBase.userID).Child("password").SetValueAsync(DataBase.password);
SceneManager.LoadScene("game");
}
else
{
username.GetComponent<InputField>().textComponent.color = Color.red;
}
}
});
}
It works just fine when I use it on unity but when I compile it and run it on my android device it doesn't send any information to the database. It does not even turn the text color to red which would indicate that the task is faulted.... Hope you can help me figure it out.
remove spaces from the project direction, including the name itself.
try to make the names of all the directories in the project space-free.

Admob Interstitial ad not showing up at all

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)

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().

Categories