Issue with Admob Interstitial Unity 3D - c#

I've followed Google Admob step by step tutorial on implementing Interstitial Ad on my 3D Unity game, but the interstitial didn't shown when running the game on my device.
Do you know what's wrong in my code, and how to fix it?
Ad Script:
private InterstitialAd interstitial;
static int loadCount = 0;
bool GameHasEnded = false;
float RestartDelay = 1.5f;
private void Start()
{
#if UNITY_ANDROID
string appId = "ca-app-pub-3940256099942544/1033173712";
#else
string appId = "unexpected_platform";
#endif
// Initialize the Google Mobile Ads SDK.
MobileAds.Initialize(appId);
this.RequestInterstitial();
if ((loadCount % 3) == 0) // only show ad every third time
{
if (this.interstitial.IsLoaded())
{
this.interstitial.Show();
}
}
}
void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().path);
loadCount = loadCount + 1;
}
private void RequestInterstitial()
{
#if UNITY_ANDROID
string adUnitId = "ca-app-pub-3940256099942544/1033173712";
#else
string adUnitId = "unexpected_platform";
#endif
// Initialize an InterstitialAd.
this.interstitial = new InterstitialAd(adUnitId);
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the interstitial with the request.
this.interstitial.LoadAd(request);
}

For me the problem seems to happen because the interstitial ad takes a while to load (sometimes up to 3 seconds). You're trying to call it too fast, and it's not loaded, so nothing happens. What I did was continually try to show the interstitial ad in void Update until it shows (using a bool called shown):
void Update () {
if (shown == false) {
ShowInterstitial();
}
}
public void ShowInterstitial()
{
if (interstitial.IsLoaded())
{
interstitial.Show();
shown = true;
} else {
Debug.Log ("Interstitial is not ready yet.");
}
}
You could also load the ad at the beginning of the level, and then only call it when the round is over.

You're trying to initalize admob and request new interstitial on every restart. You have to create one instance of AdmobController or whatever and use it.
public class AdManager{
public static AdManager instance;
private void Awake(){
if(instance == null) {
instance = this;
DontDestroyOnLoad(gameObject);
} else {
Destroy(gameObject);
return;
}
}
private void Start()
{
#if UNITY_ANDROID
string appId = "ca-app-pub-3940256099942544/1033173712";
#else
string appId = "unexpected_platform";
#endif
// Initialize the Google Mobile Ads SDK.
MobileAds.Initialize(appId);
this.RequestInterstitial();
}
public void showInterstitial(){
if ((loadCount % 3) == 0) // only show ad every third time
{
if (this.interstitial.IsLoaded())
{
this.interstitial.Show();
}
}
}
then when you want to show interstitial
AdController.instance.showInterstitial();
It may have syntax error or something but you've get the idea.

Related

How do I Clear the discord rich presence in unity

When I close the game I want the discord rich presence to clear but it still show that I'm playing the game, this my discord controller:
using Discord;
using UnityEngine;
using UnityEngine.SceneManagement;
public class DiscordController : MonoBehaviour
{
public long applicationID;
[Space]
public string details = "Walking around the world";
public string state = "Current velocity: ";
[Space]
public string largeImage = "game_logo";
public string largeText = "Discord Tutorial";
private long time;
private static bool instanceExists;
public Discord.Discord discord;
Scene scene;
void Awake()
{
// Transition the GameObject between scenes, destroy any duplicates
if (!instanceExists)
{
instanceExists = true;
DontDestroyOnLoad(gameObject);
}
else if (FindObjectsOfType(GetType()).Length > 1)
{
Destroy(gameObject);
}
}
void Start()
{
// Log in with the Application ID
discord = new Discord.Discord(applicationID, (System.UInt64)Discord.CreateFlags.NoRequireDiscord);
time = System.DateTimeOffset.Now.ToUnixTimeMilliseconds();
UpdateStatus();
}
void Update()
{
scene = SceneManager.GetActiveScene();
// Destroy the GameObject if Discord isn't running
try
{
discord.RunCallbacks();
}
catch
{
Destroy(gameObject);
}
}
void LateUpdate()
{
UpdateStatus();
}
void UpdateStatus()
{
// Update Status every frame
try
{
var activityManager = discord.GetActivityManager();
var activity = new Discord.Activity
{
Details = details,
State = state + scene.name,
Assets =
{
LargeImage = largeImage,
LargeText = largeText
},
Timestamps =
{
Start = time
}
};
activityManager.UpdateActivity(activity, (res) =>
{
if (res != Discord.Result.Ok) Debug.LogWarning("Failed connecting to Discord!");
});
}
catch
{
// If updating the status fails, Destroy the GameObject
Destroy(gameObject);
}
}
}
After I leave the game it still shows that I'm playing and I couldn't fin anything on youtube about it
Please help me to resolve this issue, I've tried myself but I couldn't fix it
Discord Image
You can use activityManager.ClearActivity() that can be found in the ActivityManager.
This method will return a Discord.Result via callback
Example:
activityManager.ClearActivity((result) =>
{
if (result == Discord.Result.Ok)
{
Console.WriteLine("Success!");
}
else
{
Console.WriteLine("Failed");
}
});
More information on this topic can be found here.

i want to implement ads in my game but there is an issue in my AdsController script for that reason the ads are not showing in my game apk

I'm facing issue in my AdsController.cs script
Everything is working fine in my game but the ads are not showing in the app
please solve this issue and also tell me where I'm wrong i think i did something wrong with my AdsController script thats why the warnings is Assets\Scripts\AdmobManager.cs(21,16): warning CS0219: The variable 'AppId' is assigned but its value is never used
either remove the variables or use them I want to use the variables, that's why the ads are not showing because the ad ids are stored in a variable but not used it means the AdMob manager doesn't know the ad ids values. Can you know how can I use these variables in my script? I think there is a problem while implementing in my script
Here is my 'AdsController.cs' Script
using UnityEngine;
public class _AdsController : MonoBehaviour
{
public GameManager gameManager_1;
public GameManager_2 gameManager_2;
public GameManager_3 gameManager_3;
public AdManager adManager;
public AdmobManager admobManager;
[Header("Ads Manager")]
public UnityadsManager unityadsManager;
bool showAds = true;
void Start()
{
if (adManager.AdNetwork == AdManager.adNetwork.Admob)
{
unityadsManager.gameObject.SetActive(false);
}
if (adManager.AdNetwork == AdManager.adNetwork.UnityAds)
{
admobManager.gameObject.SetActive(false);
}
}
void Update()
{
if (gameManager_1 != null)
{
if (gameManager_1.Succes || gameManager_1.Failed)
{
Show();
}
}
if (gameManager_2 != null)
{
if (gameManager_2.Succes || gameManager_2.Failed)
{
Show();
}
}
if (gameManager_3 != null)
{
if (gameManager_3.Succes || gameManager_3.Failed)
{
Show();
}
}
}
public void Show()
{
if (showAds)
{
if (adManager.AdNetwork == AdManager.adNetwork.Admob)
{
admobManager.ShowInterstitial();
showAds = false;
}
if (adManager.AdNetwork == AdManager.adNetwork.UnityAds)
{
unityadsManager.ShowInterstitial();
showAds = false;
}
}
}
}
Here is my 'AdmobManager.cs' Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AdmobManager : MonoBehaviour
{
public AdManager adManager;
[HideInInspector]
public bool AdmobeRewardFinished = false;
private BannerView bannerView;
private InterstitialAd interstitial;
private RewardedAd rewardedAd;
private void Awake()
{
#if UNITY_ANDROID
string AppId = "ca-app-pub-5990016123172046~4832056793";
#elif UNITY_IPHONE
string AppId = "ca-app-pub-3940256099942544~1458002511";
#else
string AppId = "unexpected_platform";
#endif
// Initialize the Google Mobile Ads SDK.
MobileAds.Initialize(initStatus => { });
AdmobeRewardFinished = false;
}
void Start()
{
if (PlayerPrefs.GetInt("ads") != 1)
{
RequestBanner();
RequestInterstitial();
}
}
public void RequestBanner()
{
#if UNITY_ANDROID
string BannerId = "ca-app-pub-5990016123172046/8196586737";
#elif UNITY_IPHONE
string BannerId = "ca-app-pub-3940256099942544/2934735716";
#else
string BannerId = "unexpected_platform";
#endif
// Create a 320x50 banner at the top of the screen.
this.bannerView = new BannerView(adManager.BannerId, AdSize.SmartBanner, AdPosition.Bottom);
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the banner with the request.
this.bannerView.LoadAd(request);
}
private void RequestInterstitial()
{
#if UNITY_ANDROID
string InterstitialId = "ca-app-pub-5990016123172046/8005015043";
#elif UNITY_IPHONE
string adUnitId = "ca-app-pub-3940256099942544/4411468910";
#else
string adUnitId = "unexpected_platform";
#endif
// Initialize an InterstitialAd.
this.interstitial = new InterstitialAd(adManager.interstitialId);
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the interstitial with the request.
this.interstitial.LoadAd(request);
}
public void ShowInterstitial()
{
if (this.interstitial.IsLoaded() && PlayerPrefs.GetInt("ads") != 1)
{
this.interstitial.Show();
}
}
}

can't reset specfic playerprefs in unity3d

I have made 2 codes to manage my interstitial ads by making the ads show every 5 mins when the player losses but the problem is that I tried to reset them when the player passes the 5 mins and press the button when he losses but it didn't work so how to reset the timer when the player presses the button?
this is the 1st code :
public int LastShownIntTime = 300;
void Start()
{
#if UNITY_ANDROID
Advertisement.Initialize(androidID);
#endif
}
public void Update()
{
LastShownIntTime = PlayerPrefs.GetInt("LastShownIntTime");
}
public void showInterstitial()
{
if (LastShownIntTime <=0)
{
showInterstitialwith5mint();
}
}
public void showInterstitialwith5mint()
{
Advertisement.Show("video");
PlayerPrefs.SetInt("LastShownIntTime", 300);
}
and the 2nd one :
public float LastShownIntTimefloat;
public int LastShownIntTime = 300;
void Start()
{
LastShownIntTime = PlayerPrefs.GetInt("LastShownIntTime");
LastShownIntTimefloat = LastShownIntTime;
}
public void Update()
{
LastShownIntTimefloat -= Time.deltaTime;
LastShownIntTime = (int)LastShownIntTimefloat;
PlayerPrefs.SetInt("LastShownIntTime", LastShownIntTime);
}
}
The main issue here:
You would have to reset the LastShownIntTimefloat in your script2!
Otherwise you simply continue overwriting it with new values reducing the value more and write it back to PlayerPrefs
→ the next time your script1 polls the value it is not reset but already overwritten by script2!
In general: You should not use PlayerPrefs in order to make two components communicate!
In your case here I wouldn't even separate the logic and bother with implementing the communication between them but rather merge them into one single component.
Then it is not necessary to read and write PlayerPrefs every frame but rather only on certain checkpoints like
Read once in Start
Write once in OnApplicationQuit
Write once in OnDestroy (This is for the case you e.g. switch Scene but don't quit the app)
Write once ever time your user loses (showInterstitial is called)
Write once when resetting the value after showing the advertisement
I would also simply directly use a float and GetFloat and SetFloat instead of converting it from and to an int.
public class MergedClass : MonoBehaviour
{
// Rather sue a FLOAT for time!
public float LastShownTime = 300;
void Start()
{
#if UNITY_ANDROID
Advertisement.Initialize(androidID);
#endif
// use 300 as default value if no PlayerPrefs found
LastShownTime = PlayerPrefs.GetFloat("LastShownTime", 300f);
}
public void Update()
{
if(LastShownTime > 0f) LastShownTime -= Time.deltaTime;
}
public void showInterstitial()
{
PlayerPrefs.SetFloat("LastShownTime", LastShownTime);
PlayerPrefs.Save();
if (LastShownTime <= 0f)
{
showInterstitialwith5mint();
}
}
public void showInterstitialwith5mint()
{
#if UNITY_ANDROID
Advertisement.Show("video");
#else
LastShownTime = 300f;
PlayerPrefs.SetFloat("LastShownTime", LastShownTime);
PlayerPrefs.Save();
}
private void OnApplicationQuit()
{
PlayerPrefs.SetFloat("LastShownTime", LastShownTime);
PlayerPrefs.Save();
}
private void OnDestroy()
{
PlayerPrefs.SetFloat("LastShownTime", LastShownTime);
PlayerPrefs.Save();
}
}

Unity/Photon PUN players don't see each other's rooms and create new ones

recently I have started creating a mobile game and decided to have a multiplayer feature. I watched youtube tutorials and got the basics but for some unknown reason players can't see each other.
What I want to do:
Connect to the server
Join the lobby
Join the room, if there's no room - create a new one
As soon as there're 2 players in one room start the game (2 players is the minumum number of players and the maximum as well)
What I do:
I build the project and get the .exe file
I run the .exe file in order to connect to the server and create a new room (I know that at the beginning there's no room yet)
I run the project in Unity
I connect to the server to join the room created in 2., but for some reason I cannot see the room and I am creating a new one
As a result I get two separate rooms with only one player in each of them instead of getting one room with two players
What I did:
I have spent last two days reading documentation and forum but to no success.
I have found similar problems and implemented the proposed solutions (like adding IsVisible = true or IsOpen = true whenever I create a new room) but in my case they didn't work
I added lots of Debug logs but my knowledge of Unity and Photon is not enough to fully use their potential
Here's the code responsible for Internet connection:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.SceneManagement;
public class PhotonLobby : MonoBehaviourPunCallbacks
{
public static PhotonLobby lobby;
public GameObject battleButton;
public GameObject cancelButton;
private void Awake(){
// creates the singleton, lives within the main menu screen
lobby = this;
}
// Start is called before the first frame update
void Start()
{
// connects to master photon server
PhotonNetwork.ConnectUsingSettings();
}
public override void OnConnectedToMaster()
{
Debug.Log("Player has connected to the Photon master server");
Debug.Log("Number of players connected to the master: " + PhotonNetwork.CountOfPlayersOnMaster);
PhotonNetwork.JoinLobby();
Debug.Log("Joined lobby");
PhotonNetwork.AutomaticallySyncScene = true;
battleButton.SetActive(true);
}
public void OnBattleButtonClicked()
{
Debug.Log("Battle button was clicked");
battleButton.SetActive(false);
cancelButton.SetActive(true);
PhotonNetwork.JoinRandomRoom();
}
public override void OnJoinRandomFailed(short returnCode, string message)
{
Debug.Log("Tried to join a random game but failed. There must be no open games available");
CreateRoom();
}
void CreateRoom()
{
Debug.Log("Trying to create a new room");
int randomRoomName = Random.Range(0,10000);
RoomOptions roomOps = new RoomOptions() {IsVisible = true, IsOpen = true, MaxPlayers = (byte) MultiplayerSetting.multiplayerSetting.maxPlayers};
PhotonNetwork.CreateRoom("Room" + randomRoomName, roomOps);
Debug.Log("Created room " + randomRoomName);
}
public override void OnCreateRoomFailed(short returnCode, string message)
{
Debug.Log("Tried to create a new room but failed. There must already be a room with the same name");
CreateRoom();
}
public void OnCancelButtonClicked()
{
Debug.Log("Cancel button was clicked");
cancelButton.SetActive(false);
battleButton.SetActive(true);
PhotonNetwork.LeaveRoom();
SceneManager.LoadScene(1);
}
}
And the code responsible for joining/creating rooms:
using System.IO;
using System.Collections;
using Photon.Pun;
using Photon.Realtime;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PhotonRoom : MonoBehaviourPunCallbacks, IInRoomCallbacks
{
// room info
public static PhotonRoom room;
private PhotonView PV;
public bool isGameLoaded;
public int currentScene;
// player info
Player[] photonPlayers;
public int playersInRoom;
public int myNumberInRoom;
public int playerInGame;
// delayed start
private bool readyToCount;
private bool readyToStart;
public float startingTime;
private float lessThanMaxPlayers;
private float atMaxPlayers;
private float timeToStart;
private void Awake()
{
// set up singleton
if(PhotonRoom.room == null)
{
PhotonRoom.room = this;
}
else
{
if(PhotonRoom.room != this)
{
Destroy(PhotonRoom.room.gameObject);
PhotonRoom.room = this;
}
}
DontDestroyOnLoad(this.gameObject);
}
public override void OnEnable()
{
// subscribe to functions
base.OnEnable();
PhotonNetwork.AddCallbackTarget(this);
SceneManager.sceneLoaded += OnSceneFinishedLoading;
}
public override void OnDisable()
{
base.OnDisable();
PhotonNetwork.RemoveCallbackTarget(this);
SceneManager.sceneLoaded -= OnSceneFinishedLoading;
}
// Start is called before the first frame update
void Start()
{
// set private variables
PV = GetComponent<PhotonView>();
readyToCount = false;
readyToStart = false;
lessThanMaxPlayers = startingTime;
atMaxPlayers = 6;
timeToStart = startingTime;
}
// Update is called once per frame
void Update()
{
// for delay start only, count down to start
if(MultiplayerSetting.multiplayerSetting.delayStart)
{
if(playersInRoom == 1)
{
RestartTimer();
}
if(!isGameLoaded)
{
if(readyToStart)
{
atMaxPlayers -= Time.deltaTime;
lessThanMaxPlayers = atMaxPlayers;
timeToStart = atMaxPlayers;
}
else if(readyToCount)
{
lessThanMaxPlayers -= Time.deltaTime;
timeToStart = lessThanMaxPlayers;
}
Debug.Log("Display time to start to the players " + timeToStart);
if(timeToStart<=0)
{
Debug.Log("We have started the game!");
StartGame();
}
}
}
}
public override void OnJoinedRoom()
{
// sets player data when we join the room
base.OnJoinedRoom();
Debug.Log("We are now in a room");
photonPlayers = PhotonNetwork.PlayerList;
playersInRoom = photonPlayers.Length;
myNumberInRoom = playersInRoom;
PhotonNetwork.NickName = myNumberInRoom.ToString();
// for delay start only
if(MultiplayerSetting.multiplayerSetting.delayStart)
{
Debug.Log("Displayer players in room out of max players possible (" + playersInRoom + ":" + MultiplayerSetting.multiplayerSetting.maxPlayers + ")");
if(playersInRoom > 1)
{
readyToCount = true;
}
if(playersInRoom == MultiplayerSetting.multiplayerSetting.maxPlayers)
{
readyToStart = true;
if(!PhotonNetwork.IsMasterClient)
return;
PhotonNetwork.CurrentRoom.IsOpen = false;
}
}
// for non delay start
else if (playersInRoom == 2)
{
Debug.Log("We have started the game!");
StartGame();
}
else {
Debug.Log("There's only 1 player");
}
}
public override void OnPlayerEnteredRoom(Player newPlayer)
{
base.OnPlayerEnteredRoom(newPlayer);
Debug.Log("A new player has joined the room");
photonPlayers = PhotonNetwork.PlayerList;
playersInRoom++;
if(MultiplayerSetting.multiplayerSetting.delayStart)
{
Debug.Log("Displayer players in room out of max players possible (" + playersInRoom + ":" + MultiplayerSetting.multiplayerSetting.maxPlayers + ")");
if(playersInRoom > 1)
{
readyToCount = true;
}
if(playersInRoom == MultiplayerSetting.multiplayerSetting.maxPlayers)
{
readyToStart = true;
if(!PhotonNetwork.IsMasterClient)
return;
PhotonNetwork.CurrentRoom.IsOpen = false;
}
}
}
void StartGame()
{
isGameLoaded = true;
if(!PhotonNetwork.IsMasterClient)
return;
if(MultiplayerSetting.multiplayerSetting.delayStart)
{
PhotonNetwork.CurrentRoom.IsOpen = false;
}
PhotonNetwork.LoadLevel(MultiplayerSetting.multiplayerSetting.multiplayerScene);
}
void RestartTimer()
{
lessThanMaxPlayers = startingTime;
timeToStart = startingTime;
atMaxPlayers = 6;
readyToCount = false;
readyToStart = false;
}
void OnSceneFinishedLoading(Scene scene, LoadSceneMode mode)
{
// called when multiplayer scene is loaded
currentScene = scene.buildIndex;
if(currentScene == MultiplayerSetting.multiplayerSetting.multiplayerScene)
{
isGameLoaded = true;
// for delay start game
if(MultiplayerSetting.multiplayerSetting.delayStart)
{
PV.RPC("RPC_LoadedGameScene", RpcTarget.MasterClient);
}
// for non delay start game
else
{
RPC_CreatePlayer();
}
}
}
[PunRPC]
public void RPC_LoadedGameScene()
{
playersInRoom++;
if(playerInGame == PhotonNetwork.PlayerList.Length)
{
PV.RPC("RPC_CreatePlayer", RpcTarget.All);
}
}
[PunRPC]
public void RPC_CreatePlayer()
{
PhotonNetwork.Instantiate(Path.Combine("PhotonPrefabs", "PhotonNetworkPlayer"),transform.position,Quaternion.identity, 0);
}
public override void OnPlayerLeftRoom(Player otherplayer)
{
base.OnPlayerLeftRoom(otherplayer);
Debug.Log(otherplayer.NickName+ "Has left the game");
playersInRoom--;
}
}
Thank you in advance for any help :)
If you connect to Photon Cloud, make sure clients are connected to the same virtual application (AppId, AppVersion) and to the same servers (Region).
If you are using the default Best Region connection method, you need to consider that clients could end up connected to two different regions.
Go through our "Matchmaking Checklist".
I have finally found the solution, the problem were regions to which my players connected. I have set the region to eu and it worked. I believe that preciously each player connected to different region.
I hope it will help someone in the future

Simple Unity game gets slow after admob integration

I made a simple 2d game with not many objects and it runs fine on my Xperia ST. But when i integrated admobs to show both banner and interstitial ads on game over screen the gameplay lags and gets slow.
My code for admob and how they are used is given below
Player Script
using UnityEngine;
using System.Collections;
public class PlayerMotion : MonoBehaviour {
public GameObject gameOverTag,spawner,camera,adObject;
SpawnScript spawnScript;
GoogleMobileAdsDemoScript adScript;
// Use this for initialization
void Awake() {
adObject=GameObject.Find("Ads");// ads is a game object which was kept from main menu screen
}
void Start () {
spawnScript= spawner.GetComponent<SpawnScript> ();
//adScript=camera.GetComponent<GoogleMobileAdsDemoScript> ();//GoogleMobileAdsDemoScript is the ad script
adScript=adObject.GetComponent<GoogleMobileAdsDemoScript> ();
adScript.hideBanner ();
adScript.requestInterstitial ();
}
// Update is called once per frame
void Update () {
//some more code
}
}
public void Movement()
{
//some code
}
void OnCollisionEnter2D(Collision2D other){
//some code
}
void OnGUI(){
if (gameOver) {
if((adScript.timesInterstitalRequested)%5==0)
adScript.ShowInterstitial ();
else
adScript.showBanner ();
//some more code
}
}
}
Here is GoogleMobileAdsDemoScript Code
using System;
using UnityEngine;
using GoogleMobileAds;
using GoogleMobileAds.Api;
// Example script showing how to invoke the Google Mobile Ads Unity plugin.
public class GoogleMobileAdsDemoScript : MonoBehaviour
{
private BannerView bannerView;
private InterstitialAd interstitial;
public int timesBannerRequested=0,timesInterstitalRequested=0;
void Awake() {
DontDestroyOnLoad (this);
}
void Start()
{
}
public void requestBanner(){
//Requesting BannerView
timesBannerRequested = timesBannerRequested + 1;
#if UNITY_EDITOR
string adUnitId = "ca-app-pub-asdas";
#elif UNITY_ANDROID
string adUnitId = "ca-app-pub-asd";
#elif UNITY_IPHONE
string adUnitId = "INSERT_IOS_BANNER_AD_UNIT_ID_HERE";
#else
string adUnitId = "unexpected_platform";
#endif
bannerView = new BannerView(adUnitId, AdSize.SmartBanner, AdPosition.Bottom);
AdRequest requestBanner = new AdRequest.Builder().Build();
bannerView.LoadAd(requestBanner);
//bannerView.Hide ();
}
public void requestInterstitial(){
timesInterstitalRequested = timesInterstitalRequested + 1;
//Requesting Interstitial
#if UNITY_EDITOR
string adUnitIdInterstitial = "ca-app-pub-dfada";
#elif UNITY_ANDROID
string adUnitIdInterstitial = "ca-app-pub-asdas";
#elif UNITY_IPHONE
string adUnitIdInterstitial = "INSERT_IOS_INTERSTITIAL_AD_UNIT_ID_HERE";
#else
string adUnitIdInterstitial = "unexpected_platform";
#endif
interstitial = new InterstitialAd(adUnitIdInterstitial);
AdRequest requestInterstitial = new AdRequest.Builder().Build();
interstitial.LoadAd(requestInterstitial);
}
public void showBanner()
{
bannerView.Show ();
}
public void destroyBanner()
{
bannerView.Destroy ();
}
public void hideBanner()
{
bannerView.Hide ();
}
public void ShowInterstitial()
{
if (interstitial.IsLoaded())
{
interstitial.Show();
}
else
{
print("Interstitial is not ready yet.");
}
}
}
Your logic seems solid from a first glance,
I would however optimize the OnGUI function. since this is the most vital function of all,
when considering the mobile hardware.
void OnGUI(){
if (gameOver) {
if(adScript.bannerShowing == false) {
if((adScript.timesInterstitalRequested)%5==0)
adScript.ShowInterstitial ();
else
adScript.showBanner ();
}
}
}
Then add a bannerShowing boolean on the GoogleMobileAdsDemoScript code and make it true when visible
and false when the banner is hidden,
its a bad idea to call ShowInterstital or showBanner multiple times in OnGUI since it all runs on a single thread.
Google Admob uses some very big 8MB DLL if you integrate that into Unity project.
Common feedback is: the App starts slower and the app loads scenes with Admob slow for the fist time.
You may try to implement native Android plugin into your Unity app. Basically that plugin would be written in Java and it would work fast.

Categories

Resources