Ok, so I’ve been trying for a while now and I can’t seem to figure out how to save the score that the player has once they die and set that to the PlayerPrefs. The way my script is set up now it saves the int score which is “0” as the high score. Here’s my script for the main menu, player, and generate.
using UnityEngine;
using System.Collections;
public class MainMenu : MonoBehaviour{
public Texture backgroundTexture;
public float guiPlacementY1;
public float guiPlacementY2;
public float guiPlacementY3;
public float guiPlacementX1;
public float guiPlacementX2;
public float guiPlacementX3;
void OnGUI()
{
GUI.DrawTexture(new Rect(0,0,Screen.width,Screen.height), backgroundTexture);
if (GUI.Button (new Rect(Screen.width * guiPlacementX1, Screen.height * guiPlacementY1, Screen.width * .5f, Screen.height * .1f), "Play Game")){
Application.LoadLevel("RunMouseRun");
}
if (GUI.Button (new Rect(Screen.width * guiPlacementX2, Screen.height * guiPlacementY2, Screen.width * .5f, Screen.height * .1f), "Options")){
print ("Clicked Options");
}
if (GUI.Button (new Rect(Screen.width * guiPlacementX1, Screen.height * guiPlacementY1, Screen.width * .5f, Screen.height * .1f), "Play Game")){
print ("Clicked Play Game");
}
if (GUI.Button (new Rect(Screen.width * guiPlacementX2, Screen.height * guiPlacementY2, Screen.width * .5f, Screen.height * .1f), "Options")){
print ("Clicked Options");
}
GUI.Label(new Rect(Screen.width * guiPlacementX3, Screen.height * guiPlacementY3, 300, 50), "High Score: " +PlayerPrefs.GetInt("HighScore"));
}
}
using UnityEngine;
public class Player : MonoBehaviour{
void Update (){
Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
if (screenPosition.x > Screen.width || screenPosition.x < 0)
{
Die();
}
}
void OnCollisionEnter2D(Collision2D other)
{
Die();
}
void Die()
{
Application.LoadLevel("MainMenu");
}
}
using UnityEngine;
public class Generate : MonoBehaviour{
public GameObject Walls;
public GameObject Ground;
public GameObject Fence;
int score = 0;
// Use this for initialization
void Start()
{
//PlayerPrefs.SetInt("HighScore", score);
StoreHighScore();
PlayerPrefs.Save();
InvokeRepeating("CreateObstacle", 4f,4f);
InvokeRepeating("CreateGround", .1f,6.8f);
InvokeRepeating("CreateObstacle1", 2f,4f);
}
// Update is called once per frame
void OnGUI ()
{
GUI.color = Color.black;
GUILayout.Label("Score:" + score.ToString());
}
void CreateObstacle()
{
Instantiate(Walls);
score++;
}
void CreateGround()
{
Instantiate(Ground);
}
void CreateObstacle1()
{
Instantiate(Fence);
score++;
}
void StoreHighScore()
{
if (score > PlayerPrefs.GetInt("HighScore"))
PlayerPrefs.SetInt("HighScore", score);
}
}