I have a button for showing rewarded advertisement. If the advertisement is loaded, I want to enable this button, also if the advertisement is not loaded, I want to disabled this button. But, the code is not working, When i have no internet connection, the button is always enabled. How can i do this issue?
Here is my code :
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RewardedShop : MonoBehaviour
{
public static RewardedShop Instance { get; set; }
private void Awake()
{
Instance = this;
}
public string appkey;
public GameObject afterRewardedScreen, mainScreen;
public Button btnWatchSHOP;
public GameObject btnActive;
RewardedGameObject[] go;
// Start is called before the first frame update
void Start()
{
IronSource.Agent.shouldTrackNetworkState(true);
IronSourceEvents.onRewardedVideoAvailabilityChangedEvent += RewardedVideoAvaibilityChangedEvent;
IronSourceEvents.onRewardedVideoAdClosedEvent += RewardedVideoAdClosedEvent;
IronSourceEvents.onRewardedVideoAdRewardedEvent += RewardedVideoAdRewardedEvent;
//IronSourceEvents.onRewardedVideoAdReadyEvent += OnRewardedVideoAdReady;
btnWatchSHOP.interactable = false;
}
public void showRewarded()
{
if (IronSource.Agent.isRewardedVideoAvailable())
{
counter = 0;
IronSource.Agent.showRewardedVideo("ShopRewarded");
}
}
void RewardedVideoAdClosedEvent()
{
IronSource.Agent.init(appkey, IronSourceAdUnits.REWARDED_VIDEO);
IronSource.Agent.shouldTrackNetworkState(true);
}
void RewardedVideoAvaibilityChangedEvent(bool available)
{
bool rewardedVideoAvailability = available;
BtnActive();
}
int counter = 0;
void RewardedVideoAdRewardedEvent(IronSourcePlacement ssp)
{
if (counter < 1)
{
RewardHandlerSHOP.Instance.Reward();
counter++;
}
}
public void Reward()
{
PlayerPrefs.SetInt("totalCoin", PlayerPrefs.GetInt("totalCoin") + 150);
GameObject.Find("TxtTotalSHOPCoin").GetComponent<Text>().text = PlayerPrefs.GetInt("totalCoin").ToString();
SoundManager.Instance.PlayEarnGoldSound();
}
public void BtnActive()
{
bool available = IronSource.Agent.isRewardedVideoAvailable();
if (available)
{
btnWatchSHOP.interactable = true;
}
else
{
btnWatchSHOP.interactable = false;
}
}
}
Related
I've created a leveling system for my game in Unity. I was able to store the level and XP amount in my Firebase database. I'm also able to display both the level and XP in gave and have it update in the database without having to manually save the data.
The problem is now that the xp bar I created that scales based on the amount of xp the user is not communicating with my database, only its self. It also resets all int variables to 0 when switching scenes or restarting the game.
My goal here is to have the progress bar update live based on the amount of xp that's stored in my database and to have it not reset after I switch scenes or reload the game.
Here's my code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class LevelSystem
{
public event EventHandler OnExperienceChanged;
public event EventHandler OnLevelChanged;
private static readonly int[] experiencePerLevel = new[] {100, 120, 145, 175, 210, 250, 295, 345, 400, 460};
private int level;
private int experience;
private int experienceToNextLevel;
private TMP_Text xpText;
public LevelSystem()
{
level = 0;
experience = 0;
experienceToNextLevel = 100;
}
public void AddExperience(int amount)
{
if (!IsMaxLevel())
{
experience += amount;
while (!IsMaxLevel() && experience >= GetExperienceToNextLevel(level))
{
//Enough experience to level up
level++;
experience -= GetExperienceToNextLevel(level);
if(OnLevelChanged != null) OnLevelChanged(this, EventArgs.Empty);
}
if(OnExperienceChanged != null) OnExperienceChanged(this, EventArgs.Empty);
}
}
public int GetLevelNumber()
{
return level;
}
public int GetXpAmount()
{
return experience;
}
public float GetExperienceNormalized()
{
if (IsMaxLevel())
{
return 1f;
}
else
{
return (float)experience / GetExperienceToNextLevel(level);
}
}
public int GetExperience()
{
return experience;
}
public int GetExperienceToNextLevel()
{
return experienceToNextLevel;
}
public int GetExperienceToNextLevel(int level)
{
if (level < experiencePerLevel.Length)
{
return experiencePerLevel[level];
}
else
{
//Level invalid
Debug.Log("Level invalid: " + level);
return 100;
}
}
public bool IsMaxLevel()
{
return IsMaxLevel(level);
}
public bool IsMaxLevel(int level)
{
return level == experiencePerLevel.Length - 1;
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Utilities.Mine;
public class LevelSystemAnimation
{
public event EventHandler OnExperienceChanged;
public event EventHandler OnLevelChanged;
private LevelSystem levelSystem;
private bool isAnimating;
private float updateTimer;
private float updateTimerMax;
private int level;
private int experience;
public LevelSystemAnimation(LevelSystem levelSystem)
{
SetLevelSystem(levelSystem);
updateTimerMax = .016f;
FunctionUpdater.Create(() => Update());
}
public void SetLevelSystem(LevelSystem levelSystem)
{
this.levelSystem = levelSystem;
level = levelSystem.GetLevelNumber();
experience = levelSystem.GetExperience();
levelSystem.OnExperienceChanged += LevelSystem_OnExperienceChanged;
levelSystem.OnLevelChanged += LevelSystem_OnLevelChanged;
}
private void LevelSystem_OnLevelChanged(object sender, System.EventArgs e)
{
isAnimating = true;
}
private void LevelSystem_OnExperienceChanged(object sender, System.EventArgs e)
{
isAnimating = true;
}
public void Update()
{
if(isAnimating)
{
updateTimer += Time.deltaTime;
while (updateTimer > updateTimerMax)
{
updateTimer -= updateTimerMax;
UpdateTypeAddExperience();
}
}
}
private void UpdateTypeAddExperience()
{
if(level < levelSystem.GetLevelNumber())
{
//Local level under target level
AddExperience();
}
else
{
//Local level equals the target level
if (experience < levelSystem.GetExperience())
{
AddExperience();
}
else
{
isAnimating = false;
}
}
}
public void AddExperience()
{
experience++;
if (experience >= levelSystem.GetExperienceToNextLevel(level))
{
level++;
experience = 0;
if(OnLevelChanged != null) OnLevelChanged(this, EventArgs.Empty);
}
if(OnExperienceChanged != null) OnExperienceChanged(this, EventArgs.Empty);
}
public int GetLevelNumber()
{
return level;
}
public int GetXpAmount()
{
return experience;
}
public float GetExperienceNormalized()
{
if (levelSystem.IsMaxLevel(level))
{
return 1f;
}
else
{
return (float)experience / levelSystem.GetExperienceToNextLevel(level);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class LevelFunction : MonoBehaviour
{
public static LevelFunction instance;
[SerializeField]
private TMP_Text levelText;
[SerializeField]
private Image experienceBarImage;
[SerializeField]
private TMP_Text xpText;
private LevelSystem levelSystem;
private LevelSystemAnimation levelSystemAnimation;
private void SetExperienceBarSize(float experienceNormalized)
{
experienceBarImage.fillAmount = experienceNormalized;
}
private void SetLevelNumber(int levelNumber)
{
levelText.text = "L" + (levelNumber + 1);
}
private void SetXpAmount(int xpAmount)
{
xpText.text = "" + xpAmount;
}
public void SetLevelSystem(LevelSystem levelSystem)
{
this.levelSystem = levelSystem;
}
public void SetLevelSystemAnimation(LevelSystemAnimation levelSystemAnimation)
{ //Set the LevelSystem object
this.levelSystemAnimation = levelSystemAnimation;
//Update the starting values
SetLevelNumber(levelSystemAnimation.GetLevelNumber());
SetExperienceBarSize(levelSystemAnimation.GetExperienceNormalized());
SetXpAmount(levelSystemAnimation.GetXpAmount());
//Subscribe to the chnaged events
levelSystemAnimation.OnExperienceChanged += LevelSystemAnimation_OnExperienceChanged;
levelSystemAnimation.OnLevelChanged += LevelSystemAnimation_OnLevelChanged;
}
private void LevelSystemAnimation_OnLevelChanged(object sender, System.EventArgs e)
{
//Level changed, update text
SetLevelNumber(levelSystemAnimation.GetLevelNumber());
}
private void LevelSystemAnimation_OnExperienceChanged(object sender, System.EventArgs e)
{
//Experience changed, update bar size
SetExperienceBarSize(levelSystemAnimation.GetExperienceNormalized());
SetXpAmount(levelSystemAnimation.GetXpAmount());
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class GainXpManager : MonoBehaviour
{
public static GainXpManager instance;
[SerializeField]
private Button collectButton;
[SerializeField]
private TMP_Text levelText;
[SerializeField]
private Image experienceBarImage;
[SerializeField]
private TMP_Text xpText;
public GameObject endGameResults;
private LevelSystem levelSystem;
private LevelSystemAnimation levelSystemAnimation;
private int level;
private int experience;
private void SetExperienceBarSize(float experienceNormalized)
{
experienceBarImage.fillAmount = experienceNormalized;
}
private void SetLevelNumber(int levelNumber)
{
levelText.text = "L" + (levelNumber + 1);
}
private void SetXpAmount(int xpAmount)
{
xpText.text = "" + xpAmount;
}
public void SetLevelSystem(LevelSystem levelSystem)
{
this.levelSystem = levelSystem;
level = levelSystem.GetLevelNumber();
experience = levelSystem.GetExperience();
}
public void SetLevelSystemAnimation(LevelSystemAnimation levelSystemAnimation)
{ //Set the LevelSystem object
this.levelSystemAnimation = levelSystemAnimation;
//Update the starting values
SetLevelNumber(levelSystemAnimation.GetLevelNumber());
SetExperienceBarSize(levelSystemAnimation.GetExperienceNormalized());
SetXpAmount(levelSystemAnimation.GetXpAmount());
//Subscribe to the chnaged events
levelSystemAnimation.OnExperienceChanged += LevelSystemAnimation_OnExperienceChanged;
levelSystemAnimation.OnLevelChanged += LevelSystemAnimation_OnLevelChanged;
}
private void LevelSystemAnimation_OnLevelChanged(object sender, System.EventArgs e)
{
//Level changed, update text
SetLevelNumber(levelSystemAnimation.GetLevelNumber());
FirebaseManager.instance.ActivateXPUpdate();
}
private void LevelSystemAnimation_OnExperienceChanged(object sender, System.EventArgs e)
{
//Experience changed, update bar size
SetExperienceBarSize(levelSystemAnimation.GetExperienceNormalized());
SetXpAmount(levelSystemAnimation.GetXpAmount());
FirebaseManager.instance.ActivateXPUpdate();
}
public void AddXpToAccount()
{
endGameResults.SetActive(false);
levelSystem.AddExperience(25);
}
}
There's more code but I think the problem can be solved with these. Any suggestions would help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GenerateUIButtons : MonoBehaviour
{
public Button buttonPrefab;
public GameObject parent;
public int numberOfButtons;
public float spaceBetweenButtons;
private Button[] buttons;
// Start is called before the first frame update
void Start()
{
buttons = new Button[Rotate.names.Length];
for (int i = 0; i < buttons.Length; i++)
{
buttons[i] = Instantiate(buttonPrefab) as Button;
buttons[i].name = Rotate.names[i];
buttons[i].transform.SetParent(parent.transform, false);
int j = i;
buttons[i].onClick.AddListener(() => ButtonClicked(j));
}
}
void ButtonClicked(int buttonNo)
{
Debug.Log("Clicked On " + buttons[buttonNo]);
}
// Update is called once per frame
void Update()
{
}
}
I want that inside the ButtonClicked when clicking on a button the text inside color will change to green and stay green for the clicked button. And if clicking on the same green button again change the color back to the original.
Like a switch.
I created a custom one few days ago, take a look on the code below.
Here you can see it in action: https://youtu.be/sl9EheTbmhE
ToggleButton.cs
using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[RequireComponent(typeof(Image))]
public class ToggleButton : MonoBehaviour, IPointerClickHandler
{
public ToggleEvent CheckedChanged = new ToggleEvent();
Image _image;
Color _originalColor;
bool _checked;
[SerializeField] Color _checkedColor;
[SerializeField] ToggleButtonGroup _group;
[SerializeField]
public bool Checked
{
get
{
return _checked;
}
set
{
if (_checked != value)
{
_checked = value;
UpdateVisual();
CheckedChanged.Invoke(this);
}
}
}
void Start()
{
_image = GetComponent<Image>();
_originalColor = _image.color;
if (_group != null)
_group.RegisterToggle(this);
}
private void UpdateVisual()
{
_image.color = Checked ? _checkedColor : _originalColor;
}
public void OnPointerClick(PointerEventData eventData)
{
Checked = !Checked;
}
[Serializable]
public class ToggleEvent : UnityEvent<ToggleButton>
{
}
}
ToggleButtonGroup.cs
using System.Collections.Generic;
using UnityEngine;
public class ToggleButtonGroup : MonoBehaviour
{
List<ToggleButton> _toggles = new List<ToggleButton>();
public void RegisterToggle(ToggleButton toggle)
{
_toggles.Add(toggle);
toggle.CheckedChanged.AddListener(HandleCheckedChanged);
}
void HandleCheckedChanged(ToggleButton toggle)
{
if (toggle.Checked)
{
foreach (var item in _toggles)
{
if (item.GetInstanceID() != toggle.GetInstanceID())
{
item.Checked = false;
}
}
}
}
}
I am making a quiz game in the unity from the unity live session quiz game tutorials everything is working fine except somehow the score isn't working when i Click the button it should add 10 score to the Score. Here are the tutorials : https://unity3d.com/learn/tutorials/topics/scripting/intro-and-setup?playlist=17117 and the code for my Game Controller :
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
public class GameController : MonoBehaviour {
public Text questionDisplayText;
public Text scoreDisplayText;
public Text timeRemainingDisplayText;
public SimpleObjectPool answerButtonObjectPool;
public Transform answerButtonParent;
public GameObject questionDisplay;
public GameObject roundEndDisplay;
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>();
// Use this for initialization
void Start ()
{
dataController = FindObjectOfType<DataController> ();
currentRoundData = dataController.GetCurrentRoundData ();
questionPool = currentRoundData.questions;
timeRemaining = currentRoundData.timeLimitInSeconds;
UpdateTimeRemainingDisplay();
playerScore = 0;
questionIndex = 0;
ShowQuestion ();
isRoundActive = true;
}
private void ShowQuestion()
{
RemoveAnswerButtons ();
QuestionData questionData = questionPool [questionIndex];
questionDisplayText.text = questionData.questionText;
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);
}
}
public void AnswerButtonClicked(bool isCorrect)
{
if (isCorrect)
{
playerScore += currentRoundData.pointsAddedForCorrectAnswer;
scoreDisplayText.text = "Score: " + playerScore.ToString();
}
if (questionPool.Length > questionIndex + 1) {
questionIndex++;
ShowQuestion ();
} else
{
EndRound();
}
}
public void EndRound()
{
isRoundActive = false;
questionDisplay.SetActive (false);
roundEndDisplay.SetActive (true);
}
public void ReturnToMenu()
{
SceneManager.LoadScene ("MenuScreen");
}
private void UpdateTimeRemainingDisplay()
{
timeRemainingDisplayText.text = "Time: " + Mathf.Round (timeRemaining).ToString ();
}
// Update is called once per frame
void Update ()
{
if (isRoundActive)
{
timeRemaining -= Time.deltaTime;
UpdateTimeRemainingDisplay();
if (timeRemaining <= 0f)
{
EndRound();
}
}
}
}
and my answer Button Code:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class AnswerButton : MonoBehaviour {
public Text answerText;
private AnswerData answerData;
private GameController GameController;
// Use this for initialization
void Start ()
{
GameController = FindObjectOfType<GameController> ();
}
public void Setup(AnswerData data)
{
answerData = data;
answerText.text = answerData.answerText;
}
public void HandleClick()
{
GameController.AnswerButtonClicked (answerData.isCorrect);
}
}
and Answer Data :
using UnityEngine;
using System.Collections;
[System.Serializable]
public class AnswerData
{
public string answerText;
public bool isCorrect;
}
If everything is working fine (the whole code gets executed correctly, which I presume at this point), you probably did not set the data correctly. In your Game Controller, you have the line
playerScore += currentRoundData.pointsAddedForCorrectAnswer;
in your AnswerButtonClicked method which should add an amount you defined to the score if the answer is correct. Since I presume that your whole code is running fine (I can't see your in-engine setup, only the code here, which looks like the one in the tutorial), this is probably the first location where to look at the error. This value is probably set in the Unity Inspector or via another script, so you may want to go check in other files or the Editor.
The next thing to check is, if the buttons are correctly linked via their event handler. This can be checked by looking at the inspector. In the tutorial series this step is done in part Click to answer at the end of the video.
I am trying to have a game, in which everyone can buy cars (and I save that data to playerprefs). So I have 9 trails for the cars in my game and I am trying to write some code so that when you press a button the car & the trail for that car will show up.
When the button next to it is clicked, it saves that data so when people restart the game, they will still have the car & trail open and won't need to press the button again.
Here's my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine; using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public Button[] TrailLevel;
public GameObject[] Cars, Trails;
public Text text;
public int CurrentCarToSpawn = 0;
private void Start()
{ }
private void FixedUpdate()
{
UpdateCar();
}
public void InstantiateCar()
{
TrailLevel[CurrentCarToSpawn].gameObject.active = false;
MineLevel[CurrentCarToSpawn+1].interactable = true;
PlayerPrefs.SetInt("TrailCountA", PlayerPrefs.GetInt("TrailCountA") + 1);
PlayerPrefs.Save();
CurrentCarToSpawn++;
UpdateCar();
}
void UpdateCar()
{
int TrailCountA= PlayerPrefs.GetInt("TrailCountA", 1);
for (int i = 0; i < TrailLevel.Length; i++)
{
if (i + 1 > TrailCountA)
{
TrailLevel.interactable = false;
}
if (TrailLevel.interactable)
{
Trains[CurrentCarToSpawn].gameObject.active = true;
Mines[CurrentCarToSpawn].gameObject.active = true;
}
}
text.text = PlayerPrefs.GetInt("TrailCountA").ToString();
}
}
From what I can see with your code, this is how I would approach it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine; using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public Button[] TrailLevel;
public GameObject[] Cars, Trails;
public Text text;
public int CurrentCarToSpawn = 0;
private void Start()
{
// Load the current car. ADDED
CurrentCarToSpawn = PlayerPrefs.getInt("savedSelection", 0);
// Since we are loading the last selection, we need to call our
// instantiation method so it can activate the appropriate
// GameObjects.
InstantiateCar();
}
private void FixedUpdate()
{
UpdateCar();
}
public void InstantiateCar()
{
TrailLevel[CurrentCarToSpawn].gameObject.active = false;
MineLevel[CurrentCarToSpawn+1].interactable = true;
PlayerPrefs.SetInt("TrailCountA", PlayerPrefs.GetInt("TrailCountA") + 1);
// Save that this is our current selection.
PlayerPrefs.SetInt("savedSelection", CurrentCarToSpawn);
PlayerPrefs.Save();
CurrentCarToSpawn++;
UpdateCar();
}
void UpdateCar()
{
int TrailCountA= PlayerPrefs.GetInt("TrailCountA", 1);
for (int i = 0; i < TrailLevel.Length; i++)
{
if (i + 1 > TrailCountA)
{
TrailLevel.interactable = false;
}
if (TrailLevel.interactable)
{
Trains[CurrentCarToSpawn].gameObject.active = true;
Mines[CurrentCarToSpawn].gameObject.active = true;
}
}
text.text = PlayerPrefs.GetInt("TrailCountA").ToString();
}
}
I am in a game jam and I have been creating a conversion script. I made a base Interact virtual void In Unity in which each interactable will use public override void Interact() and do whatever is needed. My problem is that when I call Interact() in one my scripts only main function is being called and not the overriding function. I am using Unity 2017, Csharp.
Base Interaction Script
using UnityEngine.AI;
using UnityEngine;
public class Interactable : MonoBehaviour {
private NavMeshAgent NavAgent;
private bool isInteracting;
public virtual void MoveToLocation(NavMeshAgent navMesh)
{
isInteracting = false;
this.NavAgent = navMesh;
NavAgent.stoppingDistance = 4;
NavAgent.destination = transform.position;
}
private void Update()
{
if(!isInteracting && NavAgent != null && !NavAgent.pathPending)
{
if(NavAgent.remainingDistance <= NavAgent.stoppingDistance)
{
Interact();
Debug.Log("Moving To Interactable");
isInteracting = true;
}
else
{
isInteracting = false;
}
}
}
public virtual void Interact()
{
Debug.Log("herro");
}
}
NPC Interaction Script
using UnityEngine.UI;
using UnityEngine;
public class NPC : Interactable {
//Setting Up Conversation Var
public string NPCName;
public string[] Conversation;
private int currentConversation;
//Gettig=ng UI
public CanvasGroup ConversationUI;
public Text Title;
public Text Text;
private void Start()
{
currentConversation = 0;
}
public override void Interact()
{
Debug.Log("Interacting With NPC");
//Opening UI
ConversationUI.alpha = 1;
ConversationUI.interactable = true;
ConversationUI.blocksRaycasts = true;
//Setting Up Name
Title.text = NPCName;
Text.text = Conversation[currentConversation];
}
public void NextConv()
{
currentConversation++;
if (currentConversation >= Conversation.Length)
{
ConversationUI.alpha = 0;
ConversationUI.interactable = false;
ConversationUI.blocksRaycasts = false;
}
else if (currentConversation < Conversation.Length)
{
Text.text = Conversation[currentConversation];
}
}
}