Unity Rewarded Ads coding Rewards - c#

How can i make it so after watching 2 rewarded ads all the levels in my game are unlocked and playable.
Currently i have it so you have to complete the level in order to unlock that level and be able to play it at any given time.
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);
}
}

You can use the PlayerPrefs system to track the number of ads they've watched. Increment that PlayerPref each time they watch an ad.
Then change your level configuration code to check for that PlayerPref in addition to which levels they've completed.

Unity uses PlayerPrefs to achieve level unlocking.
Level Structure:
Add a script where the level is confirmed to pass.
public int jiesuo;
jiesuo = SceneManager.GetActiveScene().buildIndex;
PlayerPrefs.SetInt("jiesuo", jiesuo);
Then add the level script to the level artboard.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class level : MonoBehaviour
{
Button[] button;
public GameObject panl;
int jiesuo1;
void Start()
{
jiesuo1 = PlayerPrefs.GetInt("jiesuo");
button = new Button[panl.transform.childCount];
for (int i = 0; i < panl.transform.childCount; i++)
{
button[i] = panl.transform.GetChild(i).GetComponent<Button>();
}
for (int i = 0; i < button.Length; i++)
{
button[i].interactable = false;
}
for (int i = 0; i < jiesuo1+1; i++)
{
button[i].interactable = true;
}
}
void Update()
{
}
}
button add:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class levelbutton : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
public void OnStartGame(int SceneNumber)
{
SceneManager.LoadScene(SceneNumber);
}
void Update()
{
}
}

Related

How to load death scene in C#/unitygames?

haven't posted on here before but I have been trying for a while to create a game and would like a death/game over sort of scene to appear when the player loses all 3 of their lives. I have a functioning game manager and my player can lose lives (they have 3). This is all being done in unity games and is 2d (idk if that helps). I currently have other stuff in my scene loader script that works fine so I will post the whole thing but I am having issues with the bottom most code!
Thank you!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneLoader : MonoBehaviour
{
public string scenename;
public GameManager GM;
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "Player")
{
SceneManager.LoadScene(scenename);
}
}
private void Deathscene()
{
if(GM.LifeTotal == 0)
{
SceneManager.LoadScene(Bob);
}
}
}
Gamemanager script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public int PotionsCollected = 0;
public int LifeTotal = 3;
public Text PotionsOutput;
public Text LifeOutput;
void Update()
{
PotionsOutput.text = "Potions: " + PotionsCollected;
LifeOutput.text = "Life: " + LifeTotal;
}
public void CollectPotion()
{
PotionsCollected++;
}
public void UsePotion()
{
PotionsCollected--;
}
public void LoseLife()
{
LifeTotal--;
}
}
What you can do is from your Unity Editor go to File->Build Settings and then drag and drop inside the active scenes window your death scene.
Then an index will be generated on the right side of the window and you can use that index to load the scene. like this:
SceneManager.LoadScene("Use your generated index");
NOTE: Use your index as a number and not as a string.
UPDATED Solution:
public void LoseLife()
{
LifeTotal--;
if(LifeTotal <= 0)
{
SceneManager.LoadScene("Use your generated index");
}
}
I supposse LoseLife() it's called when the enemy attacks your player.

How to make UnityAds appear after 3 deaths?

Right now the game shows ads each and every time the player dies. I want the ads to appear after the third death of the player. Please guide me as I am a beginner with no real knowledge of coding. Please also specify if I need to attach the script to a specific game object.
I have put the ads code below. Thanks.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public GameObject gameOverCanvas;
public GameObject Interstitial;
public int DeathCount = 0;
private void Start()
{
Time.timeScale = 1;
}
public void GameOver()
{
gameOverCanvas.SetActive(true);
Time.timeScale = 0;
DeathCount++;
}
private bool DeathCountCheck()
{
if (DeathCount == 3)
{
// Reset the variable, otherwise it will increase indefinitely and the condition will not be met in the future
Interstitial.GetComponent<InterstitialAds>().ShowInterstitial();
DeathCount = 0;
return true;
}
return false;
}
public void Replay()
{
SceneManager.LoadScene(0);
}
if "deathCount" increases each time the player dies, then when the ad is meant to show you just check that variable and reset it appropriately.
// Function that checks if there were 3 deaths
private bool DeathCountCheck()
{
if (deathCount == 3)
{
// Reset the variable, otherwise it will increase indefinitely and the condition will not be met in the future
deathCount = 0;
return true;
}
return false;
}
Then in the "ShowInterstitialAd" just add another condition
public void ShowInterstitial()
{
if (Advertisement.IsReady(interstitialID) && DeathCountCheck())
{
Advertisement.Show(interstitialID);
}
}

Why is the GUI components obsolete?

I'm currently making a remake of Dreadhalls in Unity3D. I got the code but I got 2 errors:
Assets\Standard Assets\Utility\ForcedReset.cs(6,27): error CS0619: 'GUITexture' is obsolete: 'GUITexture has been removed. Use UI.Image instead.'
Assets\Standard Assets\Utility\SimpleActivatorMenu.cs(10,16): error CS0619: 'GUIText' is obsolete: 'GUIText has been removed. Use UI.Text instead.'
I tried replacing them with the items given to me in the error, but it is still getting errors saying that the namespacee name UI is not found. I'm still not used to Unity so I need some help.
Here is the code of ForcedReset.cs:
using System;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityStandardAssets.CrossPlatformInput;
[RequireComponent(typeof (GUITexture))]
public class ForcedReset : MonoBehaviour
{
private void Update()
{
// if we have forced a reset ...
if (CrossPlatformInputManager.GetButtonDown("ResetObject"))
{
//... reload the scene
SceneManager.LoadScene(SceneManager.GetSceneAt(0).name);
}
}
}
And here is the code of SimpleActivatorMenu.cs:
using System;
using UnityEngine;
namespace UnityStandardAssets.Utility
{
public class SimpleActivatorMenu : MonoBehaviour
{
// An incredibly simple menu which, when given references
// to gameobjects in the scene
public GUIText camSwitchButton;
public GameObject[] objects;
private int m_CurrentActiveObject;
private void OnEnable()
{
// active object starts from first in array
m_CurrentActiveObject = 0;
camSwitchButton.text = objects[m_CurrentActiveObject].name;
}
public void NextCamera()
{
int nextactiveobject = m_CurrentActiveObject + 1 >= objects.Length ? 0 : m_CurrentActiveObject + 1;
for (int i = 0; i < objects.Length; i++)
{
objects[i].SetActive(i == nextactiveobject);
}
m_CurrentActiveObject = nextactiveobject;
camSwitchButton.text = objects[m_CurrentActiveObject].name;
}
}
}
Is there a problem?
GUIText and Other Elements have been Removed from the Newer Versions of Unity Due to Combability and Some Other Issues!
Fix for GUI Text
Make Sure that you Import the Following Line of Statement in your Code:-
using UnityEngine.UI;
Then, Simply Change from
public GUIText camSwitchButton;
to
public Text camSwitchButton;
Fixed for GUI Texture
This Fix Gave Me Some Warning on Other Files But Worked Properly! It Might Be Fixed in the Upcoming Updates of Unity!
Make Sure that you Import the Following Line of Statement in your Code:-
using UnityEngine.UI;
Then, Change from this Line of Code
[RequireComponent(typeof (GUITexture))]
to,
[RequireComponent(typeof(Texture))]
Hope So this Helps! I Have Checked it and it works Fine But Just Gave Me Some Warnings which I Don't Care!
But It will be Fine and will be Fixed in Some Upcoming Versions of Unity!
Fixed
For the ForcedReset.cs file change its contents with the following code:
using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using UnityStandardAssets.CrossPlatformInput;
[RequireComponent(typeof(Texture))]
public class ForcedReset : MonoBehaviour
{
private void Update()
{
// if we have forced a reset ...
if (CrossPlatformInputManager.GetButtonDown("ResetObject"))
{
//... reload the scene
SceneManager.LoadScene(SceneManager.GetSceneAt(0).name);
}
}
}
For the SimpleActivatorMenu.cs file change its contents with the following:
using System;
using UnityEngine;
using UnityEngine.UI;
namespace UnityStandardAssets.Utility
{
public class SimpleActivatorMenu : MonoBehaviour
{
// An incredibly simple menu which, when given references
// to gameobjects in the scene
public Text camSwitchButton;
public GameObject[] objects;
private int m_CurrentActiveObject;
private void OnEnable()
{
// active object starts from first in array
m_CurrentActiveObject = 0;
camSwitchButton.text = objects[m_CurrentActiveObject].name;
}
public void NextCamera()
{
int nextactiveobject = m_CurrentActiveObject + 1 >= objects.Length ? 0 : m_CurrentActiveObject + 1;
for (int i = 0; i < objects.Length; i++)
{
objects[i].SetActive(i == nextactiveobject);
}
m_CurrentActiveObject = nextactiveobject;
camSwitchButton.text = objects[m_CurrentActiveObject].name;
}
}
}

Setting levels in a quiz game

This is my first post to Stack Overflow so please be gentle. I have followed the video tutorial at https://learn.unity.com/tutorial/live-session-quiz-game-1 and have been able to successfully modify it so that images are shown as questions instead of text. The next step for me is to divide my game into Levels. I have added the appropriate extra 'Rounds' in the DataController object referred to at the end of video 3 start of video 4 so that it now looks like this:
So here is the question, if I want to add a set of buttons to a Levels page, and then add an OnClick event to each, how do I point that OnClick event specifically to the set of questions for each Level? I think I need to point the onClick at a script passing a variable that is the level number, but not sure how to do it and so far searches of StackOverflow and YouTube haven't really helped?
EDIT
I have done the following and I seem to be a lot closer:
Created a new scene called LevelSelect and added the buttons I need for the levels to it;
I created a script in the scene called LevelSelectController and to this I added the button registration script provided by Lothan;
I registered the buttons as suggested via drag and drop;
I created a Function within the LevelSelectController script called StartGame, this had one line:
Debug.Log("Button pressed is: Level " + (setLevel + 1));
I ran the script and the buttons responded as expected;
All I am struggling with now his how to get the button press to pass the integer for the level number to the allRoundData variable in the DataController. The code for each script looks like this:
DataController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class DataController : MonoBehaviour
{
public RoundData[] allRoundData;
public int currentLevel;
// Start is called before the first frame update
void Start()
{
DontDestroyOnLoad (gameObject);
SceneManager.LoadScene ("MenuScreen");
}
public RoundData GetCurrentRoundData()
{
return allRoundData [currentLevel];
}
// Update is called once per frame
void Update()
{
}
}
LevelSelectController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class LevelSelectController : MonoBehaviour
{
public List<Button> buttonsList = new List<Button>();
private DataController dataController;
public void StartGame(int setLevel)
{
Debug.Log("Button pressed is: Level " + (setLevel + 1));
}
}
GameController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameController : MonoBehaviour
{
public Text questionText;
public Image questionImage;
public SimpleObjectPool answerButtonObjectPool;
public Transform answerButtonParent;
private DataController dataController;
private RoundData currentRoundData;
private QuestionData[] questionPool;
private bool isRoundactive;
private float timeRemaining;
private int questionIndex;
private int playerScore;
private List<GameObject> answerButtonGameObjects = new List<GameObject> ();
// Start is called before the first frame update
void Start()
{
dataController = FindObjectOfType<DataController> ();
currentRoundData = dataController.GetCurrentRoundData ();
questionPool = currentRoundData.questions;
timeRemaining = currentRoundData.timeLimitInSeconds;
playerScore = 0;
questionIndex = 0;
ShowQuestion ();
isRoundactive = true;
}
private void ShowQuestion()
{
RemoveAnswerButtons ();
QuestionData questionData = questionPool[questionIndex];
questionText.text = questionData.questionText;
questionImage.transform.gameObject.SetActive(true);
questionImage.sprite = questionData.questionImage;
for (int i = 0; i < questionData.answers.Length; i++)
{
GameObject answerButtonGameObject = answerButtonObjectPool.GetObject();
answerButtonGameObjects.Add(answerButtonGameObject);
answerButtonGameObject.transform.SetParent(answerButtonParent);
AnswerButton answerButton = answerButtonGameObject.GetComponent<AnswerButton>();
answerButton.Setup(questionData.answers[i]);
}
}
private void RemoveAnswerButtons()
{
while (answerButtonGameObjects.Count > 0)
{
answerButtonObjectPool.ReturnObject(answerButtonGameObjects[0]);
answerButtonGameObjects.RemoveAt(0);
}
}
// Update is called once per frame
void Update()
{
}
}
How do I now pass the value of setLevel in LevelSelectController to currentLevel in the DataController script?
Welcome to StackOverflow!
You can do it using different ways, but one could be:
First register all the buttons:
List<Button> buttonsList = new List<Button>();
Then assign to each button the behaviour to do when onClick (registering the listener) passing the info of the corresponding DataController:
for(int i = 0; i < buttonsList.Count; i++)
{
buttonsList[i].onClick.AddListener(() => SetLevel(DataController.allRoundData[i]))
}
There are some leaps of faith in this current answer cause I don't know about your code, but if you have doubts, comment and I'll update the answer ^^
With a little extra research I was able to use a static variable along with Lothan's suggestion to get to the solution. Here is the modified code:
LevelSelectController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class LevelSelectController : MonoBehaviour
{
static public int currentLevel
public List<Button> buttonsList = new List<Button>();
void Start()
{
for(int i = 0; i < buttonsList.Count; i++)
{
int levelNum = i;
buttonsList[i].onClick.AddListener(() => {currentLevel = levelNum;});
}
}
public void StartLevel()
{
SceneManager.LoadScene ("Game");
}
}
And only one edit needed in the Start() of GameController.cs, from
currentRoundData = dataController.GetCurrentRoundData ();
to:
currentRoundData = dataController.GetCurrentRoundData (LevelSelectController.currentLevel);

Why the static bool is never set to false?

The first two scripts attached to gameobjects on one scene:
When the game start I want to play the splash screen:
In the script I'm setting the splash flag to true:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LoadScenes : MonoBehaviour
{
// Use this for initialization
void Start()
{
GameControl.splash = true;
if (!SceneManager.GetSceneByName("The Space Station").IsValid())
{
SceneManager.LoadSceneAsync(1, LoadSceneMode.Additive);
StartCoroutine(WaitForSceneLoad(SceneManager.GetSceneByName("The Space Station")));
}
}
public IEnumerator WaitForSceneLoad(Scene scene)
{
while (!scene.isLoaded)
{
yield return null;
}
SceneManager.SetActiveScene(SceneManager.GetSceneByBuildIndex(1));
}
}
When I click/press the escape key it should load back the main menu and it does but I want it to load back the main menu without playing the splash screen again:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LoadMainMenuOnclick : MonoBehaviour
{
private Scene scene;
// Use this for initialization
void Start ()
{
scene = SceneManager.GetActiveScene();
}
// Update is called once per frame
void Update ()
{
if (scene.name != "Menu" && GameControl.player.activeSelf)
{
if (Input.GetKeyDown(KeyCode.Escape))
{
SceneManager.LoadScene(0, LoadSceneMode.Additive);
StartCoroutine(WaitForSceneLoad(SceneManager.GetSceneByName("Menu")));
}
}
}
public IEnumerator WaitForSceneLoad(Scene scene)
{
while (!scene.isLoaded)
{
yield return null;
}
GameControl.splash = false;
SceneManager.SetActiveScene(SceneManager.GetSceneByBuildIndex(1));
GameControl.player.SetActive(false);
Cursor.visible = true;
}
}
This is the GameControl script static class that is not attached to any gameobject. This class is to be able to access variables in two scenes:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class GameControl
{
public static GameObject player;
public static bool splash;
}
And this script that play the splash screens is attached to gameobject on the second scene the main menu scene:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.Assertions.Must;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Splashes : UnityEngine.MonoBehaviour
{
[Header("Splash Screen")]
public bool useSplashScreen = true;
public GameObject splashesContent;
private List<Graphic> splashes = new List<Graphic>();
public float splashStayDiration = 3f;
public float splashCrossFadeTime = 1f;
void Start()
{
if (GameControl.splash == false)
useSplashScreen = GameControl.splash;
if (!useSplashScreen || splashesContent.GetComponentsInChildren<Graphic>(true).Length <= 0) return;
//if we use splash screens and we have splash screens
#region Get All Splashes
//if you build on PC Standalone - you can uncomment this
//foreach (var splash in splashesContent.GetComponentsInChildren<Graphic>(true).Where(splash => splash != splashesContent.GetComponent<Graphic>()))
//{
// splashes.Add(splash);
//}
for (var i = 0; i < splashesContent.GetComponentsInChildren<Graphic>(true).Length; i++)
{
var splash = splashesContent.GetComponentsInChildren<Graphic>(true)[i];
if (splash != splashesContent.GetComponent<Graphic>())
{
splashes.Add(splash);
}
}
#endregion
//And starting playing splashes
StartCoroutine(PlayAllSplashes());
}
private IEnumerator PlayAllSplashes()
{
//Enabling Splashes root transform
if (!splashesContent.activeSelf) splashesContent.SetActive(true);
//main loop for playing
foreach (var t in splashes)
{
t.gameObject.SetActive(true);
t.canvasRenderer.SetAlpha(0.0f);
t.CrossFadeAlpha(1, splashCrossFadeTime, false);
yield return new WaitForSeconds(splashStayDiration + splashCrossFadeTime);
t.CrossFadeAlpha(0, splashCrossFadeTime, false);
yield return new WaitForSeconds(splashCrossFadeTime);
t.gameObject.SetActive(false);
}
//Smooth main menu enabling
splashesContent.GetComponent<Graphic>().CrossFadeAlpha(0, 0.5f, false);
yield return new WaitForSeconds(0.5f);
splashesContent.gameObject.SetActive(false);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
StopCoroutine(PlayAllSplashes());
}
}
public void ExitGame()
{
Application.Quit();
}
}
I added two lines:
if (GameControl.splash == false)
useSplashScreen = GameControl.splash;
And I used a break point. When running the game it's getting to this lines and splash is true. but when I click/press the escape key it's getting to the check line but splash is still true even if I set it to false in the LoadMainMenuOnclick script.
The splash screen should be playing only when starting the game with the LoadScenes script.

Categories