Hi! I’m a beginner to Unity and looking for some help. I’ve made a simple game where you try to complete a few levels as fast as possible. I have a timer script which I want to use to save the best times in a table on the main menu. I’ve looked at some solutions with playerprefs but I’m still kinda lost and would be very thankful if someone could guide me through this.
Timer script:
public class Timercontroller : MonoBehaviour
{
public Text timeCounter;
public TimeSpan timePlaying;
public bool timerGoing;
public float elapsedTime;
public void Awake()
{
DontDestroyOnLoad(this.gameObject);
}
void Start()
{
timeCounter.text = "Time: 00:00.00";
timerGoing = false;
BeginTimer();
}
public void BeginTimer()
{
timerGoing = true;
elapsedTime = 0f;
StartCoroutine(UpdateTimer());
}
public void EndTimer()
{
timerGoing = false;
}
public IEnumerator UpdateTimer()
{
while (timerGoing)
{
elapsedTime += Time.deltaTime;
timePlaying = TimeSpan.FromSeconds(elapsedTime);
string timePlayingString = "Time: " + timePlaying.ToString("mm':'ss'.'ff");
timeCounter.text = timePlayingString;
yield return null;
}
}
void Update()
{
int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
if (currentSceneIndex == 5) {
EndTimer();
}
}
}
So PlayerPrefs will be a nice and easy way to do this. Whenever the player completes the level, you need to save that time in PlayerPrefs. However, you only want to do it if they beat the previous record (or top 3 or w/e). So, you can use an eventsystem or just a bool to determine when the player has completed the level.
This is a simple way of doing so:
private float currentTime;
private float recordTime;
public bool levelCompleted;
// Use this for initialization
void Start () {
recordTime = PlayerPrefs.GetFloat("RecordTime");
}
// Update is called once per frame
void Update () {
if(levelCompleted)
{
if(currentTime < recordTime)
{
PlayerPrefs.SetFloat("RecordTime", currentTime);
}
}
}
Then you can have your player script or level manager script determine whether or not the levelCompleted bool becomes true (or you can do it reverse and initialize the variable there and reference it in your timer script). This should get you started and hopefully a decent idea of what PlayerPrefs is doing.
Essentially, I am making a variable at Start to set as the PlayerPref. Then, you can compare it (like in the If block) to other variables of the same type. If the condition is met, then you can Set the PlayerPref, which overwrites the original and the next time you Get the PlayerPref it will have the value.
Thanks for your reply! My issue now is how do I actually display the best scores in my High score list, which at the moment is just an empty text field in the main menu?
Just like any other UI text that is dynamic. Create a Text variable in a script and then assign it to the value. Check out a tutorial with assigning variables to UI, its easy. Something like this: