Ads are working In Editor but not In Android - c#

I am trying to use ads In my game . They are properly working in Unity but not in Android. Because of I am using unity 2018.4.25f1 personal so it's supporting older version of unity monetization asset. Maybe it's a problem but here is my code of Rewarded Video CSharp file
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Advertisements;
[RequireComponent(typeof(Button))]
public class RewardedVideo : MonoBehaviour, IUnityAdsListener
{
#if UNITY_IOS
private string gameId = "3853032";
#elif UNITY_ANDROID
private string gameId = "3853033";
#endif
[SerializeField]Button myButton;
[SerializeField]GameObject errorMessage;
public string myPlacementId = "rewardedVideo";
void Start()
{
// Map the ShowRewardedVideo function to the button’s click listener:
if (myButton)
myButton.onClick.AddListener(ShowRewardedVideo);
// Initialize the Ads listener and service:
Advertisement.AddListener(this);
Advertisement.Initialize(gameId, true);
}
public void okError()
{
errorMessage.SetActive(false);
}
// Implement a function for showing a rewarded video ad:
public void ShowRewardedVideo()
{
if(Advertisement.IsReady() == true)
Advertisement.Show(myPlacementId);
else
errorMessage.SetActive(true);
}
// Implement IUnityAdsListener interface methods:
public void OnUnityAdsReady(string placementId)
{
// If the ready Placement is rewarded, activate the button:
if (placementId == myPlacementId)
{
// myButton.interactable = true;
}
}
public void OnUnityAdsDidFinish(string placementId, ShowResult showResult)
{
// Define conditional logic for each ad completion status:
if (showResult == ShowResult.Finished)
{
int levels = PlayerPrefs.GetInt("unlockedLevel", 1);
if(levels != 5)
{
PlayerPrefs.SetInt("unlockedLevel", levels+1);
}
}
else if (showResult == ShowResult.Skipped)
{
// Do not reward the user for skipping the ad.
}
else if (showResult == ShowResult.Failed)
{
Debug.LogError("The ad did not finish due to an error");
}
}
public void OnUnityAdsDidError(string message)
{
// Log the error.
}
public void OnUnityAdsDidStart(string placementId)
{
// Optional actions to take when the end-users triggers an ad.
}
}
Downloaded asset from Assets store not from package manager. I saw Unity help, unity forum, stackoverflow but nothing solved my problem
Have you any suggestion?

Related

Unity ads don't work; they won't appear on my screen

I just finished a tiny game and I wanted to learn how to implement ads, for fun. I won't post the game. I did what Unity was saying, I finished the monetization and I made a game object called Ads (I did put "andriod ID" and "iOS ID") with the following code:
using UnityEngine;
using UnityEngine.Advertisements;
public class InterstitialAdExample : MonoBehaviour, IUnityAdsLoadListener,
IUnityAdsShowListener
{
[SerializeField] string _androidAdUnitId = "Interstitial_Android";
[SerializeField] string _iOsAdUnitId = "Interstitial_iOS";
string _adUnitId;
void Awake()
{
// Get the Ad Unit ID for the current platform:
_adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
? _iOsAdUnitId
: _androidAdUnitId;
}
// Load content to the Ad Unit:
public void LoadAd()
{
// IMPORTANT! Only load content AFTER initialization (in this example, initialization is handled in a different script).
Debug.Log("Loading Ad: " + _adUnitId);
Advertisement.Load(_adUnitId, this);
}
// Show the loaded content in the Ad Unit:
public void ShowAd()
{
// Note that if the ad content wasn't previously loaded, this method will fail
Debug.Log("Showing Ad: " + _adUnitId);
Advertisement.Show(_adUnitId, this);
}
// Implement Load Listener and Show Listener interface methods:
public void OnUnityAdsAdLoaded(string adUnitId)
{
// Optionally execute code if the Ad Unit successfully loads content.
}
public void OnUnityAdsFailedToLoad(string adUnitId, UnityAdsLoadError error, string message)
{
Debug.Log($"Error loading Ad Unit: {adUnitId} - {error.ToString()} - {message}");
// Optionally execute code if the Ad Unit fails to load, such as attempting to try again.
}
public void OnUnityAdsShowFailure(string adUnitId, UnityAdsShowError error, string message)
{
Debug.Log($"Error showing Ad Unit {adUnitId}: {error.ToString()} - {message}");
// Optionally execute code if the Ad Unit fails to show, such as loading another ad.
}
public void OnUnityAdsShowStart(string adUnitId) { }
public void OnUnityAdsShowClick(string adUnitId) { }
public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState) { }
}
I don't get any errors, but the ads don't appear and I am stuck. Does anyone have any ideas?
You can try the following steps:
1.Turn on the advertising service in the project settings, as shown in the figure.
2.Import the Advertisement package in the package manager.
3.In the build settings, set the export platform to Android platform.
Add two buttons to the scene, one to load the ad and one to display the ad.
Create a new script AdsInitializer and mount it on the camera.
[SerializeField] string _androidGameId;
[SerializeField] string _iOsGameId;
[SerializeField] bool _testMode = true;
[SerializeField] bool _enablePerPlacementMode = true;
private string _gameId;
void Awake()
{
InitializeAds();
}
public void InitializeAds()
{
_gameId = (Application.platform == RuntimePlatform.IPhonePlayer)
? _iOsGameId
: _androidGameId;
Advertisement.Initialize(_gameId, _testMode, _enablePerPlacementMode, this);
}
public void OnInitializationComplete()
{
Debug.Log("Unity Ads initialization complete.");
}
public void OnInitializationFailed(UnityAdsInitializationError error, string message)
{
Debug.Log($"Unity Ads Initialization Failed: {error.ToString()} - {message}");
}
Create a new script RewardedAdsButton, which is also mounted on the camera, specify _showAdButton as the button to display the advertisement, and add the LoadAd() method in the RewardedAdsButton script to the button to load the advertisement.
void Awake()
{
// Get the Ad Unit ID for the current platform:
_adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
? _iOsAdUnitId
: _androidAdUnitId;
//Disable button until ad is ready to show
_showAdButton.interactable = false;
}
// Load content to the Ad Unit:
public void LoadAd()
{
// IMPORTANT! Only load content AFTER initialization (in this example, initialization is handled in a different script).
Debug.Log("Loading Ad: " + _adUnitId);
Advertisement.Load(_adUnitId, this);
}
// If the ad successfully loads, add a listener to the button and enable it:
public void OnUnityAdsAdLoaded(string adUnitId)
{
Debug.Log("Ad Loaded: " + adUnitId);
if (adUnitId.Equals(_adUnitId))
{
// Configure the button to call the ShowAd() method when clicked:
_showAdButton.onClick.AddListener(ShowAd);
// Enable the button for users to click:
_showAdButton.interactable = true;
}
}
// Implement a method to execute when the user clicks the button.
public void ShowAd()
{
// Disable the button:
_showAdButton.interactable = false;
// Then show the ad:
Advertisement.Show(_adUnitId, this);
}
// 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);
}
}
// Implement Load and Show Listener error callbacks:
public void OnUnityAdsFailedToLoad(string adUnitId, UnityAdsLoadError error, string message)
{
Debug.Log($"Error loading Ad Unit {adUnitId}: {error.ToString()} - {message}");
// Use the error details to determine whether to try to load another ad.
}
public void OnUnityAdsShowFailure(string adUnitId, UnityAdsShowError error, string message)
{
Debug.Log($"Error showing Ad Unit {adUnitId}: {error.ToString()} - {message}");
// Use the error details to determine whether to try to load another ad.
}
public void OnUnityAdsShowStart(string adUnitId) { }
public void OnUnityAdsShowClick(string adUnitId) { }
void OnDestroy()
{
// Clean up the button listeners:
_showAdButton.onClick.RemoveAllListeners();
}
Get the game ID of Android and iOS, and click Dashboard in the service page of the project settings.
After the webpage is opened, click Monetization => ad Units to see the game IDs of Android and Apple, you need to enable them yourself.
Go back to Unity and enter the queried id in the AdsInitializer script on the camera.
Packaged into the Android emulator to run.

Unity - Advertisment called multiple times

I'm having this problem using Unity's Advertisment. Specifically after watching the video and clicking the X button to close the video, I should give the prize to the player (go to the next level). The problem is that the OnUnityAdsDidFinish function calls if (showResult == ShowResult.Finished) multiple times. What am I doing wrong? how do I call the FindObjectOfType () .LoadNextLevel () function once; ? Thank you in advance
public class UnityAdsInterstitial : MonoBehaviour, IUnityAdsListener
{
private string gameID = "******";
//nome scelto nella DashBoard di Unity
private string interstitialID = "interstitial";
private string myPlacementId = "rewardedVideo";
public int randomHighValue = 30;
private bool TestMode = true;
private bool adsClosed = false;
public Button _button;
private void Awake()
{
_button = GetComponent<Button>();
}
void Start()
{
Debug.Log("Ads start");
_button = GameObject.Find("StartAds").GetComponent<Button>();
_button.interactable = Advertisement.IsReady(myPlacementId);
if (_button) _button.onClick.AddListener(ShowRewardedVideo);
Advertisement.Initialize(gameID, TestMode);
Advertisement.AddListener(this);
if (adsClosed)
{
adsClosed = false;
}
}
public void ShowInterstitial()
{
if (Advertisement.IsReady(interstitialID) )
{
Advertisement.Show(interstitialID);
}
}
public void ShowRewardedVideo()
{
if (Advertisement.IsReady(myPlacementId))
{
Debug.Log("Rewarded video is Ready");
Advertisement.Show(myPlacementId);
}
else
{
Debug.Log("Rewarded video is not ready at the moment! Please try again later!");
}
}
public void HideBanner()
{
Advertisement.Banner.Hide();
}
public void OnUnityAdsReady(string placementdID)
{
if (placementdID == interstitialID)
{
Debug.Log("InterstitialIsReady");
}
if (placementdID == myPlacementId)
{
Debug.Log("RewardedIsReady");
_button.interactable = true;
}
}
public void OnUnityAdsDidFinish(string placementdID, ShowResult showResult)
{
if (showResult == ShowResult.Finished)
{
// Reward the user for watching the ad to completion.
if (!adsClosed)
{
adsClosed = true;
FindObjectOfType<LevelLoader>().LoadNextLevel();
}
}
else if (showResult == ShowResult.Skipped)
{
// Do not reward the user for skipping the ad.
}
else if (showResult == ShowResult.Failed)
{
Debug.LogWarning("The ad did not finish due to an error.");
}
}
public void OnUnityAdsDidError(string message)
{
Debug.Log("OnUnityAdsDidError");
}
public void OnUnityAdsDidStart(string message)
{
Debug.Log("OnUnityAdsDidStart");
}
I would start my investigation by checking the placement id (in case there are more placements)
Checking that the callback is for the proper placement id
if (showResult == ShowResult.Finished && placementId == myPlacementId)
{
// Reward the user for watching the ad to completion.
if (!adsClosed)
{
adsClosed = true;
FindObjectOfType<LevelLoader>().LoadNextLevel();
}
}
The second would be that I only have one active instance of UnityAdsInterstitial. You can check this in debug mode by the reference of the object. If more than one instance starts from somewhere else in your code, then you should just limit to one.

is there a way to find the money made from a ad in unity

Lets say a user has watched an ad i would like to change the reward dependant on how much money i made from the ad. i don't want to use ecpm because that is a average. I want the money from a specific ad.the code i am using the default unity ad code from the tutorial. here it is
const string myPlacementId = "rewardedVideo";
public bool testMode = true;
void Start()
{
Advertisement.AddListener(this);
Advertisement.Initialize(gameId, testMode);
}
public void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
ShowRewardedVideo();
}
}
public void ShowRewardedVideo()
{
if (Advertisement.IsReady(myPlacementId))
{
Advertisement.Show(myPlacementId);
}
else
{
Debug.Log("Rewarded video is not ready at the moment! Please try again later!");
}
}
public void OnUnityAdsDidFinish(string placementId, ShowResult showResult)
{
if (showResult == ShowResult.Finished)
{
print("finishedAd");
}
else if (showResult == ShowResult.Skipped)
{
print("skip");
}
else if (showResult == ShowResult.Failed)
{
Debug.LogWarning("The ad did not finish due to an error.");
}
}
thanks in advance.

Unity Facebook login not works on Facebook App in the Android device

So i implemented Facebook SDK in my project, here the problem is FBlogin not works when i have facebook app in my android device. Please my and my team stuck in this stuff. For more details please replay to this post.
Here is the Code of my Facebook. It is working great when i uninstall facebook app in my device.
With facebook app in my android device : When open my game, facebook window is appear like do you want to continue insted of Login ask, when i click continue its not fetching my details like "Name and Profile Pic"
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Facebook.Unity;
using Facebook.MiniJSON;
using UnityEngine.UI;
using System.IO;
using System;
public class Login : MonoBehaviour
{
public string fbname;
public string get_data;
public InputField login_name;
public Image profilePic;
public Text fbNameText,FriendsText;//BABJI
public GameObject loginPanel,mainPanel;
public bool loggedIn;
void Awake ()
{
if (!FB.IsInitialized)
{
FB.Init(() =>
{
if (FB.IsInitialized)
FB.ActivateApp();
else
Debug.LogError("Couldn't initialize");
},
isGameShown =>
{
if (!isGameShown)
Time.timeScale = 0;
else
Time.timeScale = 1;
});
}
else
FB.ActivateApp();
}
void Start()
{
if (GameSaver.instance.isFBLogin) {
loginPanel.SetActive (false);
login_name.gameObject.SetActive (true);
mainPanel.SetActive (true);
// StartCoroutine (DelayLogIn ());
} else {
loginPanel.SetActive (true);
}
}
// IEnumerator DelayLogIn()
// {
// yield return new WaitForSeconds (0.1f);
//
// }
private void InitCallback ()
{
if (FB.IsInitialized) {
// Signal an app activation App Event
FB.ActivateApp();
// Continue with Facebook SDK
// ...
} else {
Debug.Log("Failed to Initialize the Facebook SDK");
}
}
private void OnHideUnity (bool isGameShown)
{
if (!isGameShown) {
// Pause the game - we will need to hide
Time.timeScale = 0;
} else {
// Resume the game - we're getting focus again
Time.timeScale = 1;
}
}
public void LoginCalled()
{
if (!FB.IsLoggedIn)
{
var perms = new List<string> (){ "public_profile", "email" };
FB.LogInWithReadPermissions (perms, AuthCallback);
}
else
{
//
}
// you are already logged in, do something
FB.API("me?fields=name", HttpMethod.GET, GetFacebookData);
FB.API("me/picture?type=square&height=128&width=128", HttpMethod.GET, GetProfilePicture);
login_name.gameObject.SetActive (true);
mainPanel.SetActive (true);
loginPanel.SetActive (false);
GameSaver.instance.isFBLogin=true;
GameSaver.instance.SaveGameData ();
}
private void AuthCallback (ILoginResult result)
{
if (FB.IsLoggedIn)
{
// AccessToken class will have session details
var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;
// Print current access token's User ID
Debug.Log(aToken.UserId);
// Print current access token's granted permissions
foreach (string perm in aToken.Permissions)
{
Debug.Log(perm);
}
FB.API("me?fields=name", Facebook.Unity.HttpMethod.GET, GetFacebookData);
//FB.API("/me/picture?redirect=false", HttpMethod.GET, GetProfilePicture);
//BABJI
FB.API("me/picture?type=square&height=128&width=128", HttpMethod.GET, GetProfilePicture);
login_name.gameObject.SetActive (true);
mainPanel.SetActive (true);
loginPanel.SetActive (false);
GameSaver.instance.isFBLogin=true;
GameSaver.instance.SaveGameData ();
//BABJI
loggedIn = FB.IsLoggedIn;
}
else
{
Debug.Log("User cancelled login");
}
}
void GetFacebookData(IResult result)
{
fbname = result.ResultDictionary["name"].ToString ();
login_name.text = fbname ;
login_name.gameObject.SetActive (true);
fbNameText.text = fbname;
Debug.Log("fbName: " + fbname);
}
private void GetProfilePicture(IGraphResult result)
{
if (result.Error == null && result.Texture != null)
{
profilePic.sprite = Sprite.Create (result.Texture, new Rect (0, 0, 128, 128), new Vector2 ());
}
}
}
depending on what we have discussed above
try this code :
public void Awake()
{
// Init Facebook SDK
if (!FB.IsInitialized)
{
// Initialize the Facebook SDK Configuration
FB.Init(InitCallback, OnHideUnity);
}
else
{
// Already initialized, signal an app activation App Event
FB.ActivateApp();
}
}
private void InitCallback() {
if (FB.IsInitialized)
{
// Signal an app activation App Event
FB.ActivateApp();
}
else
{
Debug.Log("Failed to Initialize the Facebook SDK");
}
}
private void AuthCallback(ILoginResult result)
{
if (FB.IsLoggedIn)
{
// Here is the region where u r loggged in from facebook acccount
// Just put your Logic Here
// AccessToken class will have session details
var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;
}
else
{
Debug.Log("Facebook User cancelled login");
}
}
and here is what you need to call when u press a button,
public void LoginWithFaceBook()
{
var perms = new List<string>() { "public_profile", "email" };
FB.LogInWithReadPermissions(perms, AuthCallback);
}
also use this when u logout from your application
public void FacebookLogout()
{
if (FB.IsLoggedIn)
{
FB.LogOut();
}
}

Facebook.init() function still causing null exception

Background:
I am trying to integrate facebook for a unity-android project and I can't seem to make it working, I have looked on the fb page and allot of other place but can't seem to find a what I am doing wrong.
Problem:
When trying FB.Login i get the reference exception: Facebook object is not loaded. Did you call FB.init?
Code for InitializeFB.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Facebook.MiniJSON;
using System;
public class ConncetToFaceBook : MonoBehaviour {
// Connect to facebook
void Awake () {
// Required
DontDestroyOnLoad(gameObject);
// Initialize FB SDK
enabled = false;
FB.Init(onInitComplete, OnHideUnity);
//Display id
Debug.Log (FB.UserId);
//Login to facebook
FB.Login("email,publish_actions", LoginCallback);
}
/* Helper Methods */
private void onInitComplete ()
{
enabled = true; // "enabled" is a property inherited from MonoBehaviour
if (FB.IsLoggedIn)
{
//Some Code
}
}
private void OnHideUnity(bool isGameShown)
{
//some code
}
void LoginCallback(FBResult result)
{
if (FB.IsLoggedIn)
{
OnLoggedIn();
}
}
void OnLoggedIn()
{
Debug.Log("Logged in. ID: " + FB.UserId);
}
}
Code for FB.cs.init()
public static void Init(
InitDelegate onInitComplete,
string appId = "{My app ID}", //I did put my own here. Plus I use " instead of ' because ' give me a error.
bool cookie = true,
bool logging = true,
bool status = true,
bool xfbml = true,
bool frictionlessRequests = true,
HideUnityDelegate onHideUnity = null,
string authResponse = null)
FB.Init() is asynchronous method - it doesn't make the program wait until it is finished. And your FB.Login() is called too soon, you need to call it after FB.Init() is ready - inside the onInitComplete() method.
My setup:
void FBConnect(){
if(!FB.IsInitialized){
Debug.Log("Initializing FB");
FB.Init(FBInitCallback, null,null);
} else {
Debug.Log("No need for FB init");
FBInitCallback();
}
}
private void FBInitCallback(){
Debug.Log("FB init OK");
if(!FB.IsLoggedIn){
FB.Login("email,user_friends", FBLoginCallback);
} else {
//GetHisFBDataNow();
Debug.Log("Everything is known about this guy");
}
}
private void FBLoginCallback(FBResult result){
if (result.Error != null){
Debug.Log("FB Error Response:\n" + result.Error);
} else if (!FB.IsLoggedIn) {
Debug.Log("FB Login cancelled by Player");
} else {
//GetHisFBDataNow();
Debug.Log("Now also everything is known about this guy");
}
}
Hey idk if that will help but can you try and put fb.log in init complete?

Categories