Saving the score, then using it in highscore - c#

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.

Related

How can I remove health from individual instantiated objects in unity?

So my current code removes 5 from the curhealth variable in my enemys once the bullet collides with it. But the issue is, if there is no matter which enemy i shoot and hit, it removes from every single instantiated enemy. I only want to remove health from the enemy who gets hit, how can i fix this?
Enemy.cs
using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.AI;
using UnityStandardAssets.Characters.FirstPerson;
public interface IDamagable
{
void TakeDamage(int damage);
}
public class Enemy : MonoBehaviour, IDamagable
{
//Health
public float maxHealth = 100f;
static public float curHealth = 100f;
//Health Bar
public Image healthBar;
public Transform goal;
// AI Pathfinding Variables
NavMeshAgent agent;
// Enemy Collision Variables
public float damageCooldown = 1f;
// Start is called before the first frame update
void Start()
{
curHealth = maxHealth;
}
// Update is called once per frame
void Update()
{
// Pathfinding code(?)
agent = GetComponent<NavMeshAgent>();
agent.destination = goal.position;
//Health Bar Image
healthBar.fillAmount = curHealth / maxHealth;
//Death Function
if (curHealth < 1)
{
Destroy(gameObject);
ZombieSpawner.zombieCount--;
}
}
private void OnTriggerEnter(Collider other)
{
curHealth -= Weapon.damage;
}
private void OnCollisionStay(Collision collision)
{
if (damageCooldown > 0f)
{
damageCooldown = damageCooldown - 0.1f;
}
if (collision.rigidbody.name == "Player" && damageCooldown <= 0f)
{
RigidbodyFirstPersonController.playerCurHealth = RigidbodyFirstPersonController.playerCurHealth - 10;
damageCooldown = 1f;
}
}
public void TakeDamage(int damage)
{
curHealth -= damage;
}
private void Awake()
{
//agent = GetComponent<NavMeshAgent>();
}
}
Weapon.cs
using UnityEngine;
using UnityEngine.UI;
public class GunHit
{
public float damage;
public RaycastHit raycastHit;
}
public class Weapon : MonoBehaviour
{
//Weapon Model
public GameObject weaponModel;
public LayerMask mask;
//UI Variables
public Text ammoUI;
// Weapon Variables
static public int damage = 5;
public int ammo = 12;
public int MaxAmmo = 12;
public int reserveAmmo = 90;
public AudioSource fire;
public AudioSource empty;
public bool isAiming = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
ammoUI.text = ammo + "/" + reserveAmmo;
weaponFiring();
weaponReload();
}
void weaponAiming()
{
if (Input.GetKeyDown(KeyCode.Mouse1))
{
//weaponModel.transform.position = 0, 0, 0;
}
}
// Default Position = x0, y0, z0.5
public GameObject projectilePrefab;
public GameObject gunBarrel;
void weaponFiring()
{
if (Input.GetKeyDown(KeyCode.Mouse0) && ammo > 0)
{
fire.Play();
Instantiate(projectilePrefab, gunBarrel.transform.position, gunBarrel.transform.rotation);
ammo--;
}
if (Input.GetKeyDown(KeyCode.Mouse0) && ammo == 0)
{
empty.Play();
}
}
void weaponReload()
{
if (Input.GetKeyDown(KeyCode.R))
{
if (ammo == 0)
{
if (reserveAmmo >= MaxAmmo)
{
ammo = MaxAmmo;
reserveAmmo = reserveAmmo - ammo;
}
else
{
ammo = reserveAmmo;
reserveAmmo = 0;
}
}
else if (ammo < MaxAmmo)
{
//Tiddies code
reserveAmmo += ammo;
ammo = 0;
reserveAmmo -= ammo = (reserveAmmo < MaxAmmo ? (reserveAmmo) : (MaxAmmo));
/*
* My code
* ammo = MaxAmmo - ammo;
reserveAmmo = reserveAmmo - ammo;
if (reserveAmmo > MaxAmmo)
{
ammo = MaxAmmo;
}
else if (reserveAmmo < MaxAmmo)
{
ammo = reserveAmmo;
reserveAmmo = 0;
}*/
}
}
}
}
The issue is that your current health variable is static, that means that each enemy is using the same variable for health.
Static makes the varaible global to everybody.
remove the static modifier and the variable becomes personal to each enemy ;)

Particle System not working on multiple enemies

I have a particle system for when the enemy is destroyed. I have multiple enemies coming from the same path (using the same prefab) and the particle system is only working on the first enemy. Can someone tell me why it is not working on the others as well? Thank you.
EnemyShooting scrip (this is where the piece of code is for the explosion):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyShooting : MonoBehaviour {
[SerializeField] float EnemyLaserSpeed = 10f;
[SerializeField] float EnemyLaserFireTime;
[SerializeField] GameObject LaserBulletEnemyPreFab;
[SerializeField] int MaxNumberOfHits = 1;
public Transform explosion;
int CurrentNumberOfHits = 0;
Coroutine FireCoroutine;
void OnTriggerEnter2D(Collider2D collider)
{
if(collider.gameObject.tag == "PlayerLaser")
{
if (CurrentNumberOfHits < MaxNumberOfHits)
{
CurrentNumberOfHits++;
Destroy(collider.gameObject);
Score.ScoreValue += 2;//The user will be rewarded 1 point
}
if (explosion)//EXPLOSION CODE
{
GameObject exploder = ((Transform)Instantiate(explosion, this.transform.position, this.transform.rotation)).gameObject;
Destroy(exploder, 2.0f);
}
}
}
void DestroyEnemy()
{
if(CurrentNumberOfHits >= MaxNumberOfHits)
{
Destroy(gameObject);
EnemySpawner.Instance.OnEnemyDeath(); // Tell the EnemySpawner that someone died
}
}
private void Fire()
{
FireCoroutine = StartCoroutine(ShootContinuously());
}
void BecomeVisible()
{
Fire();
}
IEnumerator ShootContinuously()
{
while (true)
{
GameObject LaserBulletEnemy = Instantiate(LaserBulletEnemyPreFab, this.transform.position, Quaternion.identity) as GameObject;
LaserBulletEnemy.GetComponent<Rigidbody2D>().velocity = new Vector2(0, EnemyLaserSpeed);
EnemyLaserFireTime = Random.Range(0.5f, 0.9f);
yield return new WaitForSeconds(EnemyLaserFireTime);
}
}
// Use this for initialization
void Start () {
BecomeVisible();
}
// Update is called once per frame
void Update () {
DestroyEnemy();
}
}
EnemySpawner : (I thought this script might help in a way so I attached it)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EnemySpawner : MonoBehaviour
{
[SerializeField] GameObject EnemyPreFab;
[SerializeField] int MaxEnemies = 30;
[SerializeField] float EnemySpawnTime = 1.00001f;
[SerializeField] GameObject FirstWaypoint;
int CurrentNumOfEnemies = 0;
public int EnemiesToNextLevel = 7;
public int KilledEnemies = 0;
public LevelManager myLevelManager;
public static EnemySpawner Instance = null;
int timesEnemyHit;
IEnumerator SpawningEnemies()
{
while (CurrentNumOfEnemies <= MaxEnemies)
{
GameObject Enemy = Instantiate(EnemyPreFab, this.transform.position, Quaternion.identity);
CurrentNumOfEnemies++;
yield return new WaitForSeconds(EnemySpawnTime);
}
}
void Start()
{
if (Instance == null)
Instance = this;
StartCoroutine(SpawningEnemies());
timesEnemyHit = 0;
if (this.gameObject.tag == "EnemyHit")
{
CurrentNumOfEnemies++;
}
}
public void OnEnemyDeath()
{
CurrentNumOfEnemies--;
/*
if (CurrentNumOfEnemies < 5)
{
// You killed everyone, change scene:
LaserLevelManager.LoadLevel("NextLevelMenu");
}
*/
KilledEnemies++;
if (KilledEnemies >= EnemiesToNextLevel)
{
LaserLevelManager.LoadLevel("NextLevelMenu");
}
}
}

An object reference is required to access non-static field in C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAttack : MonoBehaviour {
public float timeBetweenAttacks = 0.5f;
public int attackDamage = 10;
Animator anim;
GameObject Player;
PlayerHealth playerHealth;
//EnemyHeath enemyhealth;
bool playerInRange;
float timer;
private Animator animator = null;
void Awake() {
Player = GameObject.FindGameObjectWithTag ("Player");
playerHealth = Player.GetComponent<PlayerHealth> ();
//enemyHealth = GetComponent<EnemyHealth> ();
anim = GetComponent <Animator> ();
}
void Attack(Collider other) {
if (other.gameObject == Player) {
playerInRange = true;
animator.SetBool ("idle0ToAttack1", true);
}
}
void Attack1(Collider other) {
if (other.gameObject == Player) {
playerInRange = false;
}
}
void Update() {
timer +=Time.deltaTime;
if (timer >= timeBetweenAttacks /*&& enemyHealth.currentHealth > 0*/) {
AttackPlayer ();
}
if (playerHealth.currentHealth <= 0) {
Destroy (this.Player);
}
}
void AttackPlayer() {
timer = 0f;
if (PlayerHealth.currentHealth > 0) {
playerHealth.TakeDamage (attackDamage);
}
}
}
The error is giving on last method void AttackPlayer() if(PlayerHealth.currentHealth > 0).
I am making a first Person Shooter Game in Unity and if possible please tell give me some more suggestions for player dead animator code that I've written above.
void AttackPlayer()
{
timer = 0f;
if(playerHealth.currentHealth > 0)
{
playerHealth.TakeDamage(attackDamage);
}
}
I've corrected the code. It was a simple mistake of using PlayerHealth instead of what you meant which was playerHealth. Using the uppercase was referring to the class itself. The lowercase would refer to your current object defined earlier in this class.

Accessing a variable from player prefs in another scene

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.

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