- Home /
Taking high score from anther script and then displaying it
Hi. In my game the player is climbing up a wall while objects are trying to knock him off. His score is how many seconds he has survived for. I am trying to make a high score but its not going so well. Here is what I have now:
using UnityEngine;
using System.Collections;
public class AddToScore : MonoBehaviour {
private int now = 3;
public int score = 0;
private string second = " second";
private string seconds = " seconds";
public int highScore = 0;
public GUIText scoreLabel;
void Start(){
scoreLabel.text = score.ToString() + seconds;
InvokeRepeating ("AdToScore", 1, 1);
}
void Update(){
if (score > 0) {
second = " seconds";
}
if (score > highScore) {
PlayerPrefs.SetInt("highscore", score);
PlayerPrefs.Save();
highScore = score;
}
}
void AdToScore(){
if (now > 0) {
score = score + 1;
scoreLabel.text = score.ToString() + second;
}
}
}
I am sure there is something wrong with creating and saving this high score because it is not displaying in a text mesh. Here is the code for that:
using UnityEngine;
using System.Collections;
public class DisplayHighScore : MonoBehaviour {
public TextMesh highScore78;
private AddToScore addtoscoreReference;
// Use this for initialization
void Start () {
PlayerPrefs.GetInt ("highScore");
highScore78.text = addtoscoreReference.highScore + " seconds";
}
// Update is called once per frame
void Update () {
}
}
Please ignore the fact that there is a 78 in the variable name for the text mesh. I just use it to differentiate from other variables. Anyways please help me. Thanks!
Answer by ahmedbenlakhdhar · Dec 13, 2014 at 09:08 PM
Try to write (highScore78.text = addtoscoreReference.highScore + " seconds";)
in Update
instead of Start
.
If you want to execute the instruction only once then try this:
using UnityEngine;
using System.Collections;
public class DisplayHighScore : MonoBehaviour {
public TextMesh highScore78;
private AddToScore addtoscoreReference;
private bool executed = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(!executed){
highScore78.text = addtoscoreReference.highScore + " seconds";
executed = true;
}
}
}
Answer by Grim_Darknight · Dec 13, 2014 at 09:05 PM
You are missing an OnGUI() function. you can use legacy or new UI. http://docs.unity3d.com/Manual/UISystem.html
@Grim_Darknight In sorry in the documentation link I couldn't find anything. Also I am not using UI. Every button and label are visible game objects.
@Grim_Darknight Im sorry in the documentation link I couldn't find anything. Also I am not using UI. Every button and label are visible game objects.