I'm having problems with my code, you see I imported Google Admob into my project. I integrated the reward system into my AdManager script, using Github's Plugin Wiki and Documentation. However (in my AdManager script) my rewarding the user function isn't really working, I have a static int from another script that gives my player a boomerang when they pick it up in the game, buy it or receive from watching a video. Below is my AdManager script:
public class AdManager : MonoBehaviour
{
public static AdManager Instance { set; get; }
public string bannerId;
public string videoId;
private void Start()
{
Instance = this;
DontDestroyOnLoad(gameObject);
#if UNITY_EDITOR
#elif UNITY_ANDROID
Admob.Instance().initAdmob(bannerId, videoId);
Admob.Instance().setTesting(true);
Admob.Instance().loadInterstitial();
Admob.Instance().rewardedVideoEventHandler += onRewardedVideoEvent;
#endif
}
public void Reward()
{
Admob ad = Admob.Instance();
if (ad.isRewardedVideoReady())
{
ad.showRewardedVideo();
}
else
{
ad.loadRewardedVideo("ca-app-pub-2099082167446861/xxxxxxxxxx");
}
}
void onRewardedVideoEvent(string eventName, string msg)
{
WeaponScript.boomerang += 1;
Debug.Log("Well Done! You have been rewarded one Boomerang!");
Debug.Log("handler onRewardedVideoEvent---" + eventName + " " + msg);
}
}
My problem: I built the game and tried it out, watched a video got a reward (boomerang), but when I did it again (watch another reward video) I didn't get another reward (boomerang). Not sure if I'm doing it wrong. Please can anyone help me with my problem. Thank you!
Related
I made an android game. I added some ads on it with the test mode off and than I released the game to internal testers and the ads were working so than I fixed some issues in game and released the game for production on playstore.
Now that the game is up on Playstore ads are not working. Will it take some time for ads to show up? There was a popup on unity monetization dashboard that I need to update package name and I did it but ads are still not showing up although playstore listing shows that my app contain ads.
My code is :
public string gameId = "ihavemygameidhere";
public bool testMode = true;
void Start()
{
// Initialize the Ads service:
Advertisement.Initialize(gameId, testMode);
}
public void ShowInterstitialAd()
{
// Check if UnityAds ready before calling Show method:
if (Advertisement.IsReady())
{
Advertisement.Show();
}
else
{
Debug.Log("Interstitial ad not ready at the moment! Please try again later!");
}
}
When the ad is not ready, that means that the ad server has not yet sent an ad to be seen. I would recommend placing the IsReady() check in a Coroutine, then showing a loading screen UI when the player is waiting. I would also put a fail of some amount of time in case the IsReady() always fails.
[SerializeField] private GameObect LoadingUI = null;
private float waitTime = 5f;
public void ShowInterstitialAd()
{
StartCoroutine(ShowAd());
}
private IEnumerator ShowAd()
{
float currentTime = 0.0f;
LoadingUI.SetActive(true);
while(currentTime <= waitTime && !Advertisement.IsReady())
{
currenTime += Time.deltaTime;
yield return null;
}
// show the ad if it is now ready
if(Advertisement.IsReady())
{
Advertisement.Show();
}
else
{
Debug.LogError("Error: Ad was not able to be loaded in " + waitTime + " seconds!");
}
LoadingUI.SetActive(false);
}
Make sure to assign some object in the inspector for the LoadingUI object so players can not tap to view ads again or just some UI that blocks all input while the ad is attempting to load. I would use a ScreenOverlay UI as it would be rendered over everything.
I am stuck with admob rewarded ads, i can't figurate how to make event working. The problem is that my quiz game reload the scene every questions and even if i prevent the ad from destroy, the event are not firing at all. The ads are showing perfectly. I have tried multiple things but i must make a mistake somewhere... Anyone have an idea ?
Thank you very much!
using System;
using System.Collections;
using UnityEngine;
using GoogleMobileAds.Api;
public class RewardedScriptRow : MonoBehaviour
{
private RewardBasedVideoAd rewardBasedVideo;
public AudioClip GiftSound;
// Use this for initialization
void Start()
{
RequestInterstitial();
Debug.Log("Load at start");
}
public void LaunchAd() //Called from another script
{
StartCoroutine("Load");
}
private void RequestInterstitial()
{
string adUnitId = "";
#if UNITY_ANDROID
adUnitId = "ca-app-pub-00000/00000000";
#elif UNITY_IOS
adUnitId = "ca-app-pub-0000000000000";
#else
adUnitId = "unexpected_platform";
#endif
// Get singleton reward based video ad reference.
this.rewardBasedVideo = RewardBasedVideoAd.Instance;
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the interstitial with the request.
this.rewardBasedVideo.LoadAd(request, adUnitId);
rewardBasedVideo.OnAdFailedToLoad += HandleRewardBasedVideoClosed;
rewardBasedVideo.OnAdRewarded += HandleRewardBasedVideoRewarded;
}
IEnumerator Load()
{
while (!rewardBasedVideo.IsLoaded())
yield return new WaitForEndOfFrame();
yield return new WaitForSeconds(0.0f);
rewardBasedVideo.Show();
yield break;
}
//EVENT
public void HandleRewardBasedVideoRewarded(object sender, Reward args)
{
GetComponent<AudioSource>().PlayOneShot(GiftSound, 1.0F);
RequestInterstitial();
}
public void HandleRewardBasedVideoClosed(object sender, EventArgs args)
{
GetComponent<AudioSource>().PlayOneShot(GiftSound, 1.0F);
RequestInterstitial();
}
}
EDIT 1 :
using System;
using System.Collections;
using UnityEngine;
using GoogleMobileAds.Api;
public class RewardedScriptRow : MonoBehaviour
{
private RewardBasedVideoAd rewardBasedVideo;
public AudioClip GiftSound;
public static RewardedScriptRow Instance;
// Use this for initialization
void Start()
{
Instance = this;
DontDestroyOnLoad(this);
RequestRewardBasedVideo();
rewardBasedVideo.OnAdFailedToLoad += HandleRewardBasedVideoClosed;
rewardBasedVideo.OnAdRewarded += HandleRewardBasedVideoRewarded;
}
//Called after 10 questions
public void LaunchAd()
{
StartCoroutine("Load");
}
private void RequestRewardBasedVideo()
{
string adUnitId = "";
#if UNITY_ANDROID
adUnitId = "ca-app-pub-0000000/0000000000";
#elif UNITY_IOS
adUnitId = "ca-app-pub-00000/00000000";
#else
adUnitId = "unexpected_platform";
#endif
// Get singleton reward based video ad reference.
this.rewardBasedVideo = RewardBasedVideoAd.Instance;
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the interstitial with the request.
this.rewardBasedVideo.LoadAd(request, adUnitId);
}
//EVENT
public void HandleRewardBasedVideoRewarded(object sender, Reward args)
{
GetComponent<AudioSource>().PlayOneShot(GiftSound, 1.0F);
RequestRewardBasedVideo();
}
public void HandleRewardBasedVideoClosed(object sender, EventArgs args)
{
GetComponent<AudioSource>().PlayOneShot(GiftSound, 1.0F);
RequestRewardBasedVideo();
}
IEnumerator Load()
{
while (!rewardBasedVideo.IsLoaded())
yield return new WaitForEndOfFrame();
yield return new WaitForSeconds(0.0f);
rewardBasedVideo.Show();
yield break;
}
}
And this how the game work with the scenes :
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
First of all:
It seems very unwise/ illogical to call the RequestInterstial method in your event. Because by doing so, you are creating multiple subscriptions to the same events that you are already subscribed to! This can lead to very undesired/ unwanted behaviour as well as leading to Stackoverflow exceptions
It is unclear to me why you would even call RequestInterstial when the event fires. It seems to me that you would want to load a new video after the first one has been shown. Refactor your method so that you do not add the subscription events.
Move the subscription events and initialization code to your Start or Awake method.
Also you are not requesting an interstial, but a rewardbasedvideo. I'd suggest renaming to keep the code logical.
Public static RewardedScriptRow Instance;
void Start()
{
Instance = this;
DontDestroyOnLoad(this);
RequestRewardBasedVideo();
// Get singleton reward based video ad reference.
this.rewardBasedVideo = RewardBasedVideoAd.Instance;
rewardBasedVideo.OnAdFailedToLoad += HandleRewardBasedVideoClosed;
rewardBasedVideo.OnAdRewarded += HandleRewardBasedVideoRewarded;
}
private void RequestRewardBasedVideo()
{
#if UNITY_ANDROID
string appId = "ca-app-pub-3940256099942544~3347511713";
#elif UNITY_IPHONE
string appId = "ca-app-pub-3940256099942544~1458002511";
#else
string appId = "unexpected_platform";
#endif
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the rewarded video ad with the request.
this.rewardBasedVideo.LoadAd(request, adUnitId);
}
public void HandleRewardBasedVideoRewarded(object sender, Reward args)
{
GetComponent<AudioSource>().PlayOneShot(GiftSound, 1.0F);
RequestRewardBasedVideo();
}
Other than that, it should work. If you are still not getting the desirable result, try setting breakpoints while debugging and/ or use Debug.Log() inside the subscribed methods to see what's happening.
Edit: Also, if it is happening because of reloading scenes, you could try adding DontDestroyOnLoad(this); to prevent the "AdObject" from getting destroyed. I'd suggest creating this script in your very first scene and removing it from all others (to prevent duplicates).
You can then even apply the singleton pattern so you can easily access the script from within other classes.
Example:
StartCoroutine(RewardedScriptRow.Instance.LaunchAd());
I know this question has been asked several times but i got stuck even though i have implemented and tried all the solutions. I follow this tutorial for interstitial ads showing:
https://developers.google.com/admob/unity/interstitial
My main goal is to show ad whenever user taps on "Restart" button for the game.
Here is my main ad manager class (which is linked with an game object):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GoogleMobileAds.Api;
public class AdManager : MonoBehaviour {
public string interstitial_id;
public string app_id;
public InterstitialAd interstitial;
// Use this for initialization
void Start () {
//MobileAds.Initialize(app_id);
DontDestroyOnLoad(this);
Prepare_Video();
Debug.Log("Admob ilklendirildi: " + interstitial.ToString());
}
public void Show_Video()
{
Debug.Log("Reklam hazırlık durumu: " + interstitial.IsLoaded());
if (interstitial.IsLoaded()) {
Debug.Log("Reklam hazır, gösterilecek");
interstitial.Show();
}
else
{
Prepare_Video();
interstitial.Show();
}
}
public void Destroy_Video()
{
if(interstitial != null)
{
interstitial.Destroy();
}
}
public void Prepare_Video()
{
interstitial = new InterstitialAd(interstitial_id);
AdRequest request = new AdRequest.Builder().Build();
interstitial.LoadAd(request);
}
}
I call the show method in restart action:
public void RestartScene()
{
GameStatusText.gameObject.SetActive(false);
RestartButton.gameObject.SetActive(false);
MeterText.gameObject.SetActive(false);
MeterTextTop.text = "";
Time.timeScale = 1;
TimeController.TimeLeft = 50f;
FindObjectOfType<AdManager>().Show_Video();
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
you need Initialize admob first
Check what's going on with the scene that AdManager is assigned to, and if there is any changes to the scene, and do you have Google Ads unity asset installed in your game?
I have reinstalled the admob plugin and followed the instructions from the beginning. It worked. It seems like my plugin package was damaged and some files were missing.
I am developing a game for Gear VR in Unity 5.6.1p1 with Oculus Utils 1.9.0. It is on technical review now on developer console. However I keep getting entitlement error even after adding it to the project.
Here is their explanation:
It appears that your app does not support entitlement checks to prevent unauthorized use of your content. Documentation on how to add entitlement checks can be found here: https://developer.oculus.com/documentation/platform/latest/concepts/pgsg-get-started-with-sdk/
And here is my entitlement code:
public class PlatformManager : MonoBehaviour
{
public static bool entitled = false;
private static PlatformManager s_instance;
private ulong m_myID;
private string m_myOculusID;
void Awake()
{
if(s_instance != null)
{
Destroy(gameObject);
return;
}
s_instance = this;
DontDestroyOnLoad(gameObject);
Core.Initialize();
}
private void Start()
{
entitled = false;
Entitlements.IsUserEntitledToApplication().OnComplete(IsEntitledCallback);
}
void IsEntitledCallback(Message msg)
{
if(msg.IsError)
{
entitled = false;
TerminateWithError(msg);
return;
}
entitled = true;
Users.GetLoggedInUser().OnComplete(GetLoggedInUserCallback);
}
public static void TerminateWithError(Message msg)
{
Debug.Log("Error: " + msg.GetError().Message);
UnityEngine.Application.Quit();
}
void GetLoggedInUserCallback(Message<User> msg)
{
if(msg.IsError)
{
TerminateWithError(msg);
return;
}
m_myID = msg.Data.ID;
m_myOculusID = msg.Data.OculusID;
}
}
I am not doing anything with ID after entitling. Should I do something? Is there a mistake in my code? I do get true value after entitling.
My app has passed entitlement check and techical review. The code was good, but I had to add a message to let the user know that he is not entitled, and then exit the app.
I have recently been creating a game with tutorials. Unfortunately, they didn't cover a save score feature. Thanks to another user, I was able to figure out that I needed to use playerprefs. I watched tutorials online, but none of them were helpful. If you can, please help me!
Gold Per Sec Script:
using UnityEngine;
using System.Collections;
public class GoldPerSec : MonoBehaviour {
public UnityEngine.UI.Text gpsDisplay;
public Click click;
public ItemManager[] items;
void Start () {
StartCoroutine(AutoTick ());
}
void Update () {
gpsDisplay.text = GetGoldPerSec() + " Money Per Sec";
}
public float GetGoldPerSec() {
float tick = 0;
foreach (ItemManager item in items) {
tick += item.count * item.tickValue;
}
return tick;
}
public void AutoGoldPerSec() {
click.gold += GetGoldPerSec() / 10;
}
IEnumerator AutoTick() {
while (true) {
AutoGoldPerSec();
yield return new WaitForSeconds(0.10f);
}
}
}
Gold Per Click script:
using UnityEngine;
using System.Collections;
public class Click : MonoBehaviour {
public UnityEngine.UI.Text gpc;
public UnityEngine.UI.Text goldDisplay;
public float gold = 0.00f;
public int goldperclick = 1;
void Update () {
goldDisplay.text = "" + gold.ToString("F0");
gpc.text = "Money Per Click: " + goldperclick;
}
public void Clicked(){
gold += goldperclick;
}
}
My idea was for the game to save when the game is quit, and load as soon as you load the game back up. I am a complete beginner, if anyone can tell me how to do this, please tell me! Thanks! :D
You can use unity's existing functions to achieve this.
For saving data use unity's OnApplicationQuit function like this
void OnApplicationQuit() {
PlayerPrefs.SetFloat("key", value);
}
And for Restoring the values use unity's Awake function like this
void Awake(){
value = PlayerPrefs.GetFloat("key");
}
Please note that PlayerPrefs is an easy way to save data but also an very unsafe way. The player can easily manipulate his "goldValue" since it's just stored as an integer in some file on his device. PlayerPrefs should usually just be used for values the player can changed any way within in game, like volume setting etc.
EXAMPLE CODE
void Save()
{
string filename = "/filename.dat";
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath+filename);
bf.Serialize(file, goldValue); //Use can easily use e.g. a List if you want to store more date
file.Close();
}
bool Load()
{
string filename = "/filename.dat";
if (File.Exists(Application.persistentDataPath + filename))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + filename, FileMode.Open);
goldValue=(int) bf.Deserialize(file);
file.Close();
return true;
}
return false;
}
Add the following code to Click class:
void Awake()
{
LoadData();
}
void OnApplicationQuit()
{
SaveData();
}
void SaveData()
{
PlayerPrefs.SetFloat("gold",gold);
}
void LoadData()
{
gold = PlayerPrefs.GetFloat("gold",0f);
}