Accessing a variable from player prefs in another scene - c#

I'm managing my HighScore in my scene "Standard Game" by using playerprefs
I need to access my variable HighScore in my other script "SaveTest" which is in a different scene called "Main Menu" So i can destroy objects tagged DestroyUI when a highscore is reached.
Ive been googling for a bit but im not sure what im doing wrong.
Save Test
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SaveTest : MonoBehaviour
{
public ButtonReposition buttonrepositionscript;
void Start()
{
DontDestroyOnLoad(gameObject);
GameObject obj = GameObject.Find("ButtonReposition");
}
// Update is called once per frame
void Update()
{
if (GetComponent<ButtonReposition.highscore <= 100)
Destroy(GameObject.FindWithTag("DestroyUI"));
}
}
HighScore script
public class ButtonReposition : MonoBehaviour
{
public Button prefab;
public GameObject loseObject;
public int count;
public int highscore;
public Text countText;
public Text Highscoretext;
public Image lineimagestandard;
// Use this for initialization
void Start()
{
PlayerPrefs.GetInt("scorePref");
highscore = PlayerPrefs.GetInt("scorePref");
SetHighscoretext();
SetCountText();
float x = Random.Range(325f, -600f);
float y = Random.Range(250f, -450f);
Debug.Log(x + "," + y);
prefab.GetComponent<RectTransform>().anchoredPosition = new Vector2(x, y);
}
void Update()
{
if (Highscoretext.name == "highscoretext")
{
Highscoretext.text = "highscore" + highscore;
}
PlayerPrefs.SetInt("scorePref", highscore);
}

put this on your Save Test script highscore = PlayerPrefs.GetInt("scorePref");
and that's it.

Related

How do I change text with a prefab?

how do I make and change text inside a c# script?
I have this code currently but it does not work because I tell the script what the text I want to change is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class treeBreak : MonoBehaviour
{
public float woodCount = 0;
public Text woodText;
private void OnTriggerEnter2D(Collider2D other){
if (other.CompareTag("sword")){
Destroy(gameObject);
woodCount = woodCount + 1;
}
}
void Update(){
woodText.text = woodCount.ToString();
}
}
There are few problems. First if you destroy the object you lose the woodCount field because it will be destroyed with the object. Second if the object is destroyed the Update method never execute so the text wont update.
Solution 1:
The faster way to fix this is you make the woodCount static. And you update the text in the OnTriggerEnter2D.
public class treeBreak : MonoBehaviour
{
public static float woodCount = 0; // Stick with the class.
public Text woodText;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("sword"))
{
woodCount = woodCount + 1;
woodText.text = woodCount.ToString();
Destroy(gameObject);
}
}
}
Solution 1:
The better way if you separate the game logic from the UI... for example:
public class TreeBreak : MonoBehaviour
{
public WoodCounter woodCounter;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("sword"))
{
woodCounter.Collect();
Destroy(gameObject);
}
}
}
public class WoodCounter : MonoBehaviour
{
public Text woodText;
private int woodCount = 0;
public void Collect()
{
woodCount++;
woodText.text = woodCount.ToString();
}
}
PS: woodCount should be an integer if you only increase by one
Try to swap these two lines
woodCount = woodCount + 1;
Destroy(gameObject);
private void OnTriggerEnter2D(Collider2D other){
if (other.CompareTag("sword")){
woodCount = woodCount + 1;
woodText.text = woodCount.ToString();
Destroy(gameObject);
}
}

OnTriggerExit2D getting called unnecessarily

I hope you all are doing well. I have been following a Unity tutorial for a rhythm game and I have found this bug that I could not get past. Essentially, my OnTriggerExit2D is getting called too early. I'll include a picture in the conclusion of this post. I have tried logging the game object and it seems that all of my button objects suffer the same fate. I have included a link of the tutorial that I have been following in the conclusion. Any help towards figuring this out would be helpful.
Tutorial Link: https://www.youtube.com/watch?v=PMfhS-kEvc0&ab_channel=gamesplusjames
What my game looks like, the missed shows up when I've hit it.
Debug Output
GameManager
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public AudioSource theMusic;
public bool startPlaying;
public BeatScroller theBS;
public static GameManager instance;
public int currentScore;
public int scorePerNote = 100;
public int scorePerGoodNote = 125;
public int scorePerPerfectNote = 150;
public int currentMultiplier;
public int multiplierTracker;
public int [] multiplierTresholds;
public Text scoreText;
public Text multiText;
// Start is called before the first frame update
void Start()
{
instance = this;
scoreText.text = "Score: 0";
multiText.text = "Multiplier: x1";
currentMultiplier = 1;
}
// Update is called once per frame
void Update()
{
if(!startPlaying){
if(Input.anyKeyDown){
startPlaying = true;
theBS.hasStarted = true;
theMusic.Play();
}
}
}
public void NoteHit(){
Debug.Log("Note Hit On Time");
if(currentMultiplier-1 < multiplierTresholds.Length){
multiplierTracker++;
if(multiplierTresholds[currentMultiplier-1] <= multiplierTracker){
multiplierTracker = 0;
currentMultiplier++;
}
}
multiText.text = "Multiplier: x"+currentMultiplier;
//currentScore += scorePerNote * currentMultiplier;
scoreText.text = "Score: "+currentScore;
}
public void NormalHit(){
currentScore += scorePerNote * currentMultiplier;
NoteHit();
}
public void GoodHit(){
currentScore += scorePerGoodNote * currentMultiplier;
NoteHit();
}
public void PerfectHit(){
currentScore += scorePerPerfectNote * currentMultiplier;
NoteHit();
}
public void NoteMissed(){
Debug.Log("MISSED!");
multiText.text = "Multiplier: x1";
}
}
BeatScroller
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BeatScroller : MonoBehaviour
{
public float beatTempo;
public bool hasStarted;
// Start is called before the first frame update
void Start()
{
beatTempo = beatTempo / 60f;
}
// Update is called once per frame
void Update()
{
if(!hasStarted){
}else{
transform.position -= new Vector3(0f, beatTempo*Time.deltaTime, 0f);
}
}
}
ButtonController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ButtonController : MonoBehaviour
{
// Start is called before the first frame update
private SpriteRenderer theSR;
public Sprite defaultImage;
public Sprite pressedImage;
public KeyCode keyToPress;
void Start()
{
theSR = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(keyToPress))
{
theSR.sprite = pressedImage;
}
if(Input.GetKeyUp(keyToPress))
{
theSR.sprite = defaultImage;
}
}
}
noteObject
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class noteObject : MonoBehaviour
{
public bool canBePressed;
public KeyCode KeyToPress;
public GameObject hitEffect, goodEffect, perfectEffect, missedEffect;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyToPress))
{
if(canBePressed)
{
gameObject.SetActive(false);
if(Mathf.Abs(transform.position.y) > 0.25){
GameManager.instance.NormalHit();
Debug.Log("Normal Hit!");
Instantiate(hitEffect,transform.position, hitEffect.transform.rotation);
}else if(Mathf.Abs(transform.position.y) > 0.05f){
GameManager.instance.GoodHit();
Debug.Log("Good Hit!!");
Instantiate(goodEffect,transform.position, goodEffect.transform.rotation);
}else{
GameManager.instance.PerfectHit();
Debug.Log("PERFECT HIT!!!");
Instantiate(perfectEffect,transform.position, perfectEffect.transform.rotation);
}
}
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Activator")
{
canBePressed = true;
}
}
private void OnTriggerExit2D(Collider2D other)
{
if(other.tag == "Activator")
{
Debug.Log("Exited collider on game object: "+ other.gameObject.name);
canBePressed = false;
GameManager.instance.NoteMissed();
Instantiate(missedEffect,transform.position, missedEffect.transform.rotation);
}
}
}
EffectObject
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EffectObject : MonoBehaviour
{
public float lifeTime = 1f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Destroy(gameObject, lifeTime);
}
}
Hmm ... You say that OnTriggerExit2D is called to early? I assume it's called when the elements are still inside one another? If that's the case I guess your bounding boxes don't have the right size, or the right shape. I see arrows, do they have a rectangular bounding box or a polygon one that follows their shape? Are all your bounding boxes the right size?
I figured out what was wrong thanks to AdrAs's comment.
Turns out I had to check the y position of my arrow and collider were well enough below the height of my button box collider. In addition to that, I reshaped my colliders. I found that this code did the trick for me. Thank You All For the Nudges in the right direction.
noteObject -> new OnTriggerExit2D
private void OnTriggerExit2D(Collider2D other)
{
if(other.tag == "Activator" && transform.position.y < -0.32)
{
Debug.Log("Exited collider on game object: "+ other.gameObject.name);
canBePressed = false;
GameManager.instance.NoteMissed();
Instantiate(missedEffect,transform.position, missedEffect.transform.rotation);
}
}

Saving the score, then using it in highscore

I have a script that gives you 1 point every 1 second.
I was wondering how to save the score as a high score. I know about PlayerPref, but I can't get my head around it. I've also tried out several other explanations.
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class score : MonoBehaviour
{
private Text scoreText;
private float PIPS;
public GameObject gameOverScore;
public GameObject Player;
public static float scoreAmount;
public void Start()
{
scoreText = GetComponent<Text>();
scoreAmount = 0.0f;
PIPS = 1.0f;
}
public void Update()
{
if (Player.activeInHierarchy == true)
{
scoreText.text = scoreAmount.ToString("F0");
scoreAmount += PIPS * Time.deltaTime;
}
else
{
scoreText.enabled = false;
gameOverScore.GetComponent<TextMeshProUGUI>().text = scoreAmount.ToString("F0");
}
}
}
Here is an Instance from one of my Scripts -->
int HighScore = PlayerPerfs.GetInt("HighScore", 0) //If playing First Time Score = 0
void Save()
{
if(ScoreUpdate.CurrentScore > HighScore) //Check if CurrentScore is more than HighScore
{
PlayerPrefs.SetInt("HighScore", ScoreUpdate.CurrentScore);//Save New High Score
}
}
You Now Just Need To Call This Function Save() whenever the Game get complete or player dies (if dies at any point)
Edit : Replace Your Variables on place of ScoreUpdate
While this is not the ideal way, you can use playerprefs on Awake and OnDisable().
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class score : MonoBehaviour
{
private Text scoreText;
private float PIPS;
public GameObject gameOverScore;
public GameObject Player;
public static float scoreAmount;
public float HighScore;
public void Start()
{
scoreText = GetComponent<Text>();
scoreAmount = 0.0f;
PIPS = 1.0f;
}
private void OnDisable()
{
// this will save the highscore in playerprefs when the game ends[application quit].
PlayerPrefs.SetFloat("HighScore", HighScore);
}
private void Awake()
{
// this will load the highscore from playerprefs
HighScore = PlayerPrefs.GetFloat("HighScore");
}
public void Update()
{
if (Player.activeInHierarchy == true)
{
scoreText.text = scoreAmount.ToString("F0");
scoreAmount += PIPS * Time.deltaTime;
if (scoreAmount > HighScore)
{
HighScore = scoreAmount;
}
}
else
{
scoreText.enabled = false;
gameOverScore.GetComponent<TextMeshProUGUI>().text = scoreAmount.ToString("F0");
}
}
}
let me know if this helps.

Creating a target system

I'm making a target in Unity that looks like a dartboard with three different levels of scoring depending on where you shoot. The issue is that the Score Text wont change when I shoot on the target. I'm a novice and I "translated" below code from Javascript and wondering if you experts could see
if there is any issues with the code?
GlobalScore (attached this to an empty gameObject. I draged the text 'ScoreNumber' to ScoreText slot in Unity)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GlobalScore : MonoBehaviour {
public static int CurrentScore;
public int InternalScore;
public GameObject ScoreText;
void Update () {
InternalScore = CurrentScore;
ScoreText.GetComponent<Text>().text = "" + InternalScore;
}
}
ZScore25 (created 3 scripts (ZScore25, ZScore50, ZScore100) which I attached to the three cylinder gameObject I created)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ZScore25 : MonoBehaviour
{
void DeductPoints(int DamageAmount)
{
GlobalScore.CurrentScore += 25;
}
}
HandgunDamage Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HandGunDamage : MonoBehaviour {
public int DamageAmount = 5;
public float TargetDistance;
public float AllowedRange = 15.0f;
void Update () {
if (GlobalAmmo.LoadedAmmo >= 1) {
if (Input.GetButtonDown("Fire1"))
{
RaycastHit Shot;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out Shot))
{
TargetDistance = Shot.distance;
if (TargetDistance < AllowedRange)
{
Shot.transform.SendMessage("DeductPoints", DamageAmount, SendMessageOptions.DontRequireReceiver);
}
}
}
}
}
}
Debug.Log (or breakpoints) help you to see where the problem lies. I tested your case with minor changes and the score text value was changing.
I replaced ZScore25,50,100 scripts with a single ZScore script that has score as public field which you can set in the editor.
public class ZScore : MonoBehaviour {
public int Score;
public void DeductPoints() {
Debug.Log("CurrentScore += " + Score);
GlobalScore.CurrentScore += Score;
}
}
..and then I used raycast (the example script below was attached to camera):
void Update () {
if (Input.GetMouseButtonDown(0)) {
var lookAtPos = Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane));
transform.LookAt (lookAtPos);
RaycastHit Shot;
if (Physics.Raycast(transform.position, transform.forward, out Shot))
{
Debug.Log ("Raycast hit");
var score = Shot.transform.GetComponent<ZScore> ();
if (score != null) {
Debug.Log ("Hit ZScore component");
score.DeductPoints ();
}
}
}
}

Basic purchase system in Unity3d

In my game exists a opportunity to obtain a COIN, with a certain amount it is possible to release new skins.
Currently the coin score, are being stored correctly.
I have UI canvas where there skins options, I want to know how to do to be purchased these skins if the player has enough coins, or that nothing happens if it does not have enough.
Follow the codes below.
CoinScore
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class BeeCoinScore: MonoBehaviour
{
public static BeeCoinScore instance;
public static int coin = 0;
public int currentCoin = 0;
string highScoreKey = "totalCoin";
Text CoinScore; // Reference to the Text component.
void Awake ()
{
// Set up the reference.
CoinScore = GetComponent <Text> ();
}
void Start(){
//Get the highScore from player prefs if it is there, 0 otherwise.
coin = PlayerPrefs.GetInt(highScoreKey, 0);
}
public void AddBeeCoinScore (int _point) {
coin += _point;
GetComponent<Text> ().text = "Bee Coins: " + coin;
}
void Update ()
{
// Set the displayed text to be the word "Score" followed by the score value.
CoinScore.text = "Bee Coins: " + coin;
}
void OnDisable(){
//If our scoree is greter than highscore, set new higscore and save.
if(coin>currentCoin){
PlayerPrefs.SetInt(highScoreKey, coin);
PlayerPrefs.Save();
}
}
}
Script to add points to CoinScore
using UnityEngine;
using System.Collections;
public class BeeCoin : MonoBehaviour {
public int point;
private float timeVida;
public float tempoMaximoVida;
private BeeCoinScore coin;
AudioSource coinCollectSound;
void Awake() {
coin = GameObject.FindGameObjectWithTag ("BeeCoin").GetComponent<BeeCoinScore> () as BeeCoinScore;
}
// Use this for initialization
void Start () {
coinCollectSound = GameObject.Find("SpawnControllerBeeCoin").GetComponent<AudioSource>();
}
void OnCollisionEnter2D(Collision2D colisor)
{
if (colisor.gameObject.CompareTag ("Bee")) {
coinCollectSound.Play ();
coin.AddBeeCoinScore (point);
Destroy (gameObject);
}
if (colisor.gameObject.tag == "Floor") {
Destroy (gameObject, 1f);
}
}
}
My UI canvas SHOP It's pretty basic, it has 4 images related skins, with price: 100, 200, 300 and 400 coins, 4 buttons to buy below each image, and a button to leave.
C# if possible.
I solve my problem.
On the "buy" button have attached the script BuySkin
And the script BeeCoinScore i added TakeBeeScore,
deleted: if (coin> current Coin) {}, into the void OnDisable
Now it is working perfectly.
BuySkin Script.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class BuySkin : MonoBehaviour {
public int price;
public void OnClick()
{
if (BeeCoinScore.coin >= price) {
BeeCoinScore.coin -= price;
Debug.Log ("New skin added");
}
if (BeeCoinScore.coin < price) {
Debug.Log ("Need more coins!");
}
}
}
BeeCoinScore script.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class BeeCoinScore: MonoBehaviour
{
public static BeeCoinScore instance;
public static int coin = 0;
public int currentCoin = 0;
string totalCoinKey = "totalCoin";
Text CoinScore; // Reference to the Text component.
void Awake ()
{
// Set up the reference.
CoinScore = GetComponent <Text> ();
}
public void Start(){
//Get the highScore from player prefs if it is there, 0 otherwise.
coin = PlayerPrefs.GetInt(totalCoinKey, 0);
}
public void AddBeeCoinScore (int _point) {
coin += _point;
GetComponent<Text> ().text = "Bee Coins: " + coin;
}
public void TakeBeeCoinScore (int _point) {
coin -= _point;
GetComponent<Text> ().text = "Bee Coins: " + coin;
}
void Update ()
{
// Set the displayed text to be the word "Score" followed by the score value.
CoinScore.text = "Bee Coins: " + coin;
}
void OnDisable(){
PlayerPrefs.SetInt(totalCoinKey, coin);
PlayerPrefs.Save();
}
}

Categories