I’m making a survival shooter game, and I’m trying to make it so when I kill an enemy and add points to my score, its added to the high score and it saves after each play. I have the script to add score, but I don’t think I’m doing high score right. I want the normal score to count up on the screen, and the high score to count up with it on another part of the screen, and when I stop the game and play again, the high score is still up on the screen. But when I play, the high score text replaces the score text, and it doesn’t even count up when I kill an enemy. Could someone help me with this please?
public class ScoreManager : MonoBehaviour
{
public static int score;
public static int highScore;
Text scoreText;
Text highScoreText;
void Awake ()
{
scoreText = GetComponent <Text> ();
highScoreText = GetComponent<Text>();
score = 0;
highScore = 0;
highScoreText.text = PlayerPrefs.GetInt("High Score", 0).ToString();
}
void Update ()
{
scoreText.text = "Score: " + score;
highScoreText.text = "High Score: " + highScore;
if(score>PlayerPrefs.GetInt("High Score", 0))
{
PlayerPrefs.SetInt("High Score", score);
highScoreText.text = score.ToString();
}
}
}
Here’s the enemy health script for adding to score when enemy dies. It’s in the enemySinking function.
public class EnemyHealth : MonoBehaviour
{
public int startingHealth = 100;
public int currentHealth;
public float sinkSpeed = 2.5f;
public int scoreValue = 10;
public AudioClip deathClip;
Animator anim;
AudioSource enemyAudio;
ParticleSystem hitParticles;
CapsuleCollider capsuleCollider;
bool isDead;
bool isSinking;
void Awake ()
{
anim = GetComponent <Animator> ();
enemyAudio = GetComponent <AudioSource> ();
hitParticles = GetComponentInChildren <ParticleSystem> ();
capsuleCollider = GetComponent <CapsuleCollider> ();
currentHealth = startingHealth;
}
void Update ()
{
if(isSinking)
{
transform.Translate (-Vector3.up * sinkSpeed * Time.deltaTime);
}
}
public void TakeDamage (int amount, Vector3 hitPoint)
{
if(isDead)
return;
enemyAudio.Play ();
currentHealth -= amount;
hitParticles.transform.position = hitPoint;
hitParticles.Play();
if(currentHealth <= 0)
{
Death ();
}
}
void Death ()
{
isDead = true;
capsuleCollider.isTrigger = true;
anim.SetTrigger ("Dead");
enemyAudio.clip = deathClip;
enemyAudio.Play ();
}
public void StartSinking ()
{
GetComponent <UnityEngine.AI.NavMeshAgent> ().enabled = false;
GetComponent <Rigidbody> ().isKinematic = true;
isSinking = true;
ScoreManager.score += scoreValue;
Destroy (gameObject, 2f);
}