Show Result Unity ADS rewards - c#

When you pause the game, there is a button where you can click and view a non-skippable video at the end of this video. I want to implement the following:
If the video is watched to the end they gain 1 extra heart (max 3 full hearts) and get a chat box or alert dialog thanking.
If the video does not open, fully load or something goes wrong, they get nothing and a chat box or alert dialog appears.
Currently the video loads, But when the video ends, the prize is not received (1 extra heart), what is wrong in my code?
Below are the button ads
using UnityEngine;
using System.Collections;
using UnityEngine.Advertisements;
using UnityEngine.UI;
public class Ads : MonoBehaviour {
public Button getAds;
private Hearts heart;
void OnEnable ()
{
getAds.onClick.AddListener (() => GetAds (getAds));
}
private void GetAds ( Button buttonPressed)
{
if (buttonPressed == getAds) {
Advertisement.Initialize ("XXXXXX", true);
Advertisement.IsReady ("rewardedVideo");
Advertisement.Show ("rewardedVideo");
}
}
public void HandleShowResult (ShowResult result)
{
switch (result)
{
case ShowResult.Finished:
heart = GameObject.FindGameObjectWithTag ("Hearts").GetComponent<Hearts> () as Hearts;
heart.AddHeart ();
break;
case ShowResult.Skipped:
Debug.Log("The ad was skipped before reaching the end.");
break;
case ShowResult.Failed:
Debug.LogError("The ad failed to be shown.");
break;
}
}
void OnDisable ()
{
getAds.onClick.RemoveAllListeners ();
}
}
Below current hearts system script
using UnityEngine;
using System.Collections;
public class Hearts : MonoBehaviour {
public Texture2D[]initialHeart;
private int hearts;
private int currentHearts;
void Start () {
GetComponent<GUITexture>().texture = initialHeart[0];
hearts = initialHeart.Length;
}
void Update () {
}
public bool TakeHeart()
{
if (hearts < 0) {
return false;
}
if (currentHearts < (hearts - 1)) {
currentHearts += 1;
GetComponent<GUITexture> ().texture = initialHeart [currentHearts];
return true;
} else {
return false;
}
}
public bool AddHeart() {
if (currentHearts > 0) {
currentHearts -= 1;
GetComponent<GUITexture> ().texture = initialHeart [currentHearts];
return true;
} else {
return false;
}
}
}

Your code is missing the most important part which is
ShowOptions options = new ShowOptions();
options.resultCallback = HandleShowResult;
Advertisement.Show(zoneId, options);
Without it, HandleShowResult wont be called and you won't know what happened after ad has been displayed. Also score wont increment either. I went ahead to implement a coroutine which makes sure that everything is fine before displaying ads. This is was not tested but any problem can easily be fixed. Errors are displayed with red color. Green means success.
public class Ads : MonoBehaviour
{
public string gameId;
public string zoneId;
public Button getAds;
private Hearts heart;
void OnEnable()
{
getAds.onClick.AddListener(() => GetAds(getAds));
}
private void GetAds(Button buttonPressed)
{
if (buttonPressed == getAds)
{
//Wait for ad to show. The timeout time is 3 seconds
StartCoroutine(showAdsWithTimeOut(3));
}
}
public void HandleShowResult(ShowResult result)
{
switch (result)
{
case ShowResult.Finished:
heart = GameObject.FindGameObjectWithTag("Hearts").GetComponent<Hearts>() as Hearts;
heart.AddHeart();
Debug.Log("<color=green>The ad was skipped before reaching the end.</color>");
break;
case ShowResult.Skipped:
Debug.Log("<color=yellow>The ad was skipped before reaching the end.</color>");
break;
case ShowResult.Failed:
Debug.LogError("<color=red>The ad failed to be shown.</color>");
break;
}
}
IEnumerator showAdsWithTimeOut(float timeOut)
{
//Check if ad is supported on this platform
if (!Advertisement.isSupported)
{
Debug.LogError("<color=red>Ad is NOT supported</color>");
yield break; //Exit coroutine function because ad is not supported
}
Debug.Log("<color=green>Ad is supported</color>");
//Initialize ad if it has not been initialized
if (!Advertisement.isInitialized)
{
//Initialize ad
Advertisement.Initialize(gameId, true);
}
float counter = 0;
bool adIsReady = false;
// Wait for timeOut seconds until ad is ready
while(counter<timeOut){
counter += Time.deltaTime;
if( Advertisement.IsReady (zoneId)){
adIsReady = true;
break; //Ad is //Ad is ready, Break while loop and continue program
}
yield return null;
}
//Check if ad is not ready after waiting
if(!adIsReady){
Debug.LogError("<color=red>Ad failed to be ready in " + timeOut + " seconds. Exited function</color>");
yield break; //Exit coroutine function because ad is not ready
}
Debug.Log("<color=green>Ad is ready</color>");
//Check if zoneID is empty or null
if (string.IsNullOrEmpty(zoneId))
{
Debug.Log("<color=red>zoneId is null or empty. Exited function</color>");
yield break; //Exit coroutine function because zoneId null
}
Debug.Log("<color=green>ZoneId is OK</color>");
//Everything Looks fine. Finally show ad (Missing this part in your code)
ShowOptions options = new ShowOptions();
options.resultCallback = HandleShowResult;
Advertisement.Show(zoneId, options);
}
void OnDisable()
{
getAds.onClick.RemoveAllListeners();
}
}

Related

delay in update method in Unity

I am making a badminton simulator in unity, where the opponent is a set of video clips. I am trying to add some delay to my update method so theres some time between two clips of the opponent. However this delay only applies to the video clips and not the shuttle that arrives from behind the video.
My Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Video;
public class Video_Player : MonoBehaviour
{
public VideoPlayer activeCam, otherCam;
public List<VideoClip> playlist = new List<VideoClip>();
public GameObject shuttle;
VideoClip nextClip;
private bool Timer;
void Start()
{
Shuffle(playlist);
// play the first video in the playlist
PrepareNextPlaylistClip();
SwitchCams(activeCam);
Timer=false;
// setup an event to automatically call SwitchCams() when we finish playing
activeCam.loopPointReached += SwitchCams;
otherCam.loopPointReached += SwitchCams;
shuttle.SetActive(false);
}
void Update()
{
if (playlist.Count == 0)
return;
if(!Timer)
{
StartCoroutine(CountDown(5));
if (nextClip == null && activeCam.time >= activeCam.clip.length - 0.1)
{
PrepareNextPlaylistClip();
shuttle.SetActive(false);
}
if(activeCam.time >= 1.0f && activeCam.time <= 2.95f)
{
Debug.Log("start:"+activeCam.time);
shuttle.SetActive(true);
}
else
//if(activeCam.time >= 2.95f || activeCam.time <= 1.0f)
{
Debug.Log("end:"+activeCam.time);
shuttle.SetActive(false);
}
}
}
void SwitchCams(VideoPlayer thisCam)
{
activeCam = otherCam;
otherCam = thisCam;
activeCam.targetCameraAlpha = 1f;
otherCam.targetCameraAlpha = 0f;
Debug.Log("new clip: " + nextClip.name);
nextClip = null;
}
void PrepareNextPlaylistClip()
{
nextClip = playlist[0];
otherCam.clip = nextClip;
otherCam.Play();
playlist.RemoveAt(0);
}
//delay couroutine
IEnumerator CountDown(float delay)
{
Timer = true;
yield return new WaitForSeconds(delay);
Timer= false;
}
// randomize the video playlist
public static void Shuffle<T>(IList<T> playlist)
{
int n = playlist.Count;
while (n > 1)
{
n--;
int k = Random.Range(0, n);
T value = playlist[k];
playlist[k] = playlist[n];
playlist[n] = value;
}
}
}
Forgive me if I'm misunderstanding your code but rather than having it all in Update() couldn't you just have it in an IEnumerator like this?
void Start()
{
Shuffle(playlist);
// play the first video in the playlist
PrepareNextPlaylistClip();
SwitchCams(activeCam);
activeCam.loopPointReached += SwitchCams;
otherCam.loopPointReached += SwitchCams;
shuttle.SetActive(false);
//Run the function on start
StartCoroutine(Function());
}
IEnumerator Function()
{
while(true)
{
if(playlist.Count == 0)
{
//If you have no clips left exit out of the loop
break;
}
if(nextClip == null)
{
//If you have clips left load the next clip
shuttle.SetActive(false);
PrepareNextPlaylistClip();
}
yield return new WaitForSeconds(1); //This is your delay
//Execute the code you want to run after the delay here
}
}

Quick question about restarting levels on fail

I got a quick question for you. I have already everything prepared. I am making a simple launching game, where you need to kill all enemies (not time-based) to pass to the next level. I have 2 methods GoToNextLevel() and AllMonsterDied(); .
Need to make something like player have 3 attempts (3 launchings whenever he wants not based on time).
Then every launch checks if any monster left. If does just show 1 attemps less. After 3 times just restart scene.
Thanks a lot since I am new to both c# and unity that would mean the world to me.
public class LevelController: MonoBehaviour
{
[SerializeField] string _nextLevelName;
Monster[] _monsters;
void OnEnable()
{
_monsters = FindObjectsOfType<Monster>();
}
void Update()
{
int currentLevel = SceneManager.GetActiveScene().buildIndex;
if (currentLevel >= PlayerPrefs.GetInt("levelsUnlocked"))
{
PlayerPrefs.SetInt("levelsUnlocked", currentLevel + 1);
}
if (MonsterAreAllDead() )
{
GoToNextLevel();
}
Debug.Log("Level" + PlayerPrefs.GetInt("levelsUnlocked") + "UNLOCKED");
}
void GoToNextLevel()
{
Debug.Log("Go to next level" + _nextLevelName);
SceneManager.LoadScene(_nextLevelName);
}
bool MonsterAreAllDead()
{
foreach (var monster in _monsters)
{
if (monster.gameObject.activeSelf)
return false;
}
return true;
}
}
Line from Monster.cs
private void OnCollisionEnter2D(Collision2D collision)
{
if (SouldDieFromCollision(collision))
{
tickSource.Play();
StartCoroutine(Die());
}
}
IEnumerator Die()
{
_hasDied =true;
GetComponent<SpriteRenderer>().sprite=_deadsprite;
_particleSystem.Play();
yield return new WaitForSeconds(1);
gameObject.SetActive(false);
}
Let's say you want the next level launch attempt happen when the player hits N key on the keyboard.
When the player hits the key, check if all monsters are dead. If so, call GoToNextLeve(), otherwise take off 1 attempt from the attempts available and restart the current scene.
int attempts;
void OnEnable()
{
attempts = 3;
}
void Update()
{
if (Input.GetKeyUp(KeyCode.H)
{
TryGoToNextLevel();
}
}
void TryGoToNextLevel()
{
if (MonsterAreAllDead() )
{
GoToNextLevel();
}
else
{
attempts--;
}
if (attempts <= 0)
{
SceneManager.LoadScene(
SceneManager.GetActiveScene().name);
}
}

How to get user (Info Account player) in Facebook Instant Game from unity

I am having problems with my Instant game Facebook. I use FB.Init () to create connections and get information. It works fine when I run on unity but when building Webgl and uploading Instant Game FB.Init () My seems to be inactive, I tried checking it but didn't get any changes inside.
void Start() {
FB.Init(setInit, onHideUnity);
}
private void setInit() {
if (FB.IsLoggedIn) {
nameDo.text = "Name 5";
Debug.Log("Set init loggedIn");
} else {
nameDo.text = "Name 4";
Debug.Log("Set init not loggedIn");
login();
}
}
private void onHideUnity(bool isShowUnity) {
if (isShowUnity) {
Time.timeScale = 0;
} else {
Time.timeScale = 1;
}
}

Unity and Visual Studio - Issues with a button not working

So I downloaded the assets file of the final version of the Sloan Kelly Card Game Project from YouTube Link to the video where you can download it in the description and I was playing around with the game it was all working fine.
I then re-opened the game the project the next day and the 'Stick Button' is no longer working. It appears on screen and appears intractable but it will not press.
I made a couple of changes to the code to make it easier to read but didn't think i had changed anything to do with this button. The rest of the code runs fine just this one button.
I'm unsure how to link my project assets package on this sight, but I can show you the code for the button and was just wondering if anyone can see the problem straight away / could you tell me how to link the whole file so you can get a better look at what is happening.
Thanks in advance
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GameController : MonoBehaviour
{
int dealersFirstCard = -1;
public CardStack player;
public CardStack dealer;
public CardStack deck;
public Button hitButton;
public Button stickButton;
public Button playAgainButton;
public Text winnerText;
/*
* Cards dealt to each player
* First player hits/sticks/bust
* Dealer's turn unyil minimum of 17 value in hand
* Dealers cards: first card is hidden, other cards are facing
*/
#region Hit
public void Hit()
{
player.Push(deck.Pop());
if (player.HandValue() > 21)
{
hitButton.interactable = false;
stickButton.interactable = false;
StartCoroutine(DealersTurn());
}
}
#endregion
#region Stick
public void Stick()
{
hitButton.interactable = false;
stickButton.interactable = false;
StartCoroutine(DealersTurn());
}
#endregion
#region Play Again
public void PlayAgain()
{
playAgainButton.interactable = false;
player.GetComponent<CardStackView>().Clear();
dealer.GetComponent<CardStackView>().Clear();
deck.GetComponent<CardStackView>().Clear();
deck.CreateDeck();
winnerText.text = "";
hitButton.interactable = true;
stickButton.interactable = true;
dealersFirstCard = -1;
StartGame();
}
#endregion
void Start()
{
StartGame();
}
void StartGame()
{
for (int i = 0; i < 2; i++)
{
player.Push(deck.Pop());
HitDealer();
}
}
void HitDealer()
{
int card = deck.Pop();
if (dealersFirstCard < 0)
{
dealersFirstCard = card;
}
dealer.Push(card);
if (dealer.CardCount >= 2)
{
CardStackView view = dealer.GetComponent<CardStackView>();
view.Toggle(card, true);
}
}
#region Dealers turn
IEnumerator DealersTurn()
{
hitButton.interactable = false;
stickButton.interactable = false;
CardStackView view = dealer.GetComponent<CardStackView>();
view.Toggle(dealersFirstCard, true);
view.ShowCards();
yield return new WaitForSeconds(1f);
while (dealer.HandValue() < 17)
{
HitDealer();
yield return new WaitForSeconds(1f);
}
if (player.HandValue() > 21 || (dealer.HandValue() >= player.HandValue() && dealer.HandValue() <= 21))
{
winnerText.text = "You Lose!";
}
else if (dealer.HandValue() > 21 || (player.HandValue() <= 21 && player.HandValue() > dealer.HandValue()))
{
winnerText.text = "You Win!";
}
else
{
winnerText.text = "The house wins!";
}
yield return new WaitForSeconds(1f);
playAgainButton.interactable = true;
}
#endregion
}

A pause menu using a button and click

I'd like to know how I can pause and unpause menu from the same button using the mouse pointer when I click on it.
Lets say I have this. C#
void Update () {
if (Button_Pause.OnPointerClick()) {
if(!active){
PauseGame();
}
else{
ResumeGame();
}
active = !active;
}
}
public void PauseGame()
{
Button_Pause = Button_Pause.GetComponent<Button> ();
Canvas_PauseMenu.enabled = true;
Button_Exit.enabled = true;
Button_Pause.enabled = true;
}
public void ResumeGame()
{
Canvas_PauseMenu.enabled = false;
Button_Exit.enabled = false;
Button_Pause.enabled = false;
}
In the first line, where I call the OnPointerClick I'm just guessing because I don't know what to do. What I've searched around, using click to show something it's having a TimeScale or something like that.
¿Can anyone help moi? Please.
Add a listener for your button and in your pause script set timescale to zero to pause the game
[SerializeField] private Button MyButton = null; // assign in the editor
void Start() { MyButton.onClick.AddListener(() => { pause();});
}
void pause(){
if (Time.timeScale == 1)
{
Time.timeScale = 0;
}
else
{
Time.timeScale = 1;
}
}
I managed to solve the issue. It might not be efficient but it does what I need.
I created 2 buttons in the same place. Those buttons are represented with different sprites (Pause & Play). "Pause" is visible since the start. When I click on it, the menu pops up, the "Pause" stop being active and the "Play" sprite button activates and pops up too. When I click on it, I unpause and goes back to the "Pause" sprite visible in the screen.
void Start () {
Canvas_PauseMenu = Canvas_PauseMenu.GetComponent<Canvas> ();
Button_Pause = Button_Pause.GetComponent<Button> ();
Button_Resume = Button_Resume.GetComponent<Button> ();
Canvas_PauseMenu.enabled = false;
Button_Resume.enabled = false;
Button_Resume.gameObject.SetActive (false);
}
// Update is called once per frame
public void PauseTest () {
if(!active){
PauseGame();
}
else{
ResumeGame();
}
}
public void BackToMainMenu()
{
Application.LoadLevel (0);
}
public void PauseGame()
{
Canvas_PauseMenu.enabled = true;
Button_Exit.enabled = true;
Button_Pause.enabled = false;
Button_Pause.gameObject.SetActive (false);
Button_Resume.enabled = true;
Button_Resume.gameObject.SetActive (true);
active = true;
Time.timeScale = 0;
}
public void ResumeGame()
{
Canvas_PauseMenu.enabled = false;
Button_Exit.enabled = false;
Button_Pause.enabled = true;
Button_Pause.gameObject.SetActive (true);
Button_Resume.enabled = false;
Button_Resume.gameObject.SetActive (false);
active = false;
Time.timeScale = 1;
}

Categories

Resources