Hey Unity! I’m trying to make a script to count the playtime of the player.
using UnityEngine;
using TMPro;
public class PlaytimeCounter : MonoBehaviour
{
//Le Variables
private float playSeconds;
private float playMinutes;
private float playHours;
private float playDays;
//Starting Value If New
private const int startTimeCount = 0;
//Le Displays
public TextMeshPro SecondsDisplay;
public TextMeshPro MinutesDisplay;
public TextMeshPro HoursDisplay;
public TextMeshPro DaysDisplay;
void Start()
{
//Loads values if exist, else set to starting value
playSeconds = PlayerPrefs.GetFloat("", startTimeCount);
playMinutes = PlayerPrefs.GetFloat("", startTimeCount);
playHours = PlayerPrefs.GetFloat("", startTimeCount);
playDays = PlayerPrefs.GetFloat("", startTimeCount);
}
void Update()
{
//Update time
playSeconds += Time.deltaTime;
//Update other values if overlap
if (playSeconds > 59)
{
playMinutes += 1;
playSeconds = 0;
}
if (playMinutes > 59)
{
playHours += 1;
playMinutes = 0;
}
if (playHours > 23)
{
playDays += 1;
playHours = 0;
}
//Save the values
PlayerPrefs.SetFloat("", playSeconds);
PlayerPrefs.SetFloat("", playMinutes);
PlayerPrefs.SetFloat("", playHours);
PlayerPrefs.SetFloat("", playDays);
//Update the displays
int DisplaySeconds = Mathf.CeilToInt(playSeconds);
SecondsDisplay.text = "Seconds: " + DisplaySeconds.ToString();
int DisplayMinutes = Mathf.CeilToInt(playMinutes);
MinutesDisplay.text = "Minutes: " + DisplayMinutes.ToString();
int DisplayHours = Mathf.CeilToInt(playHours);
HoursDisplay.text = "Hours: " + DisplayHours.ToString();
int DisplayDays = Mathf.CeilToInt(playDays);
DaysDisplay.text = "Days: " + DisplayDays.ToString();
}
}
For some reason, every time I test this, none of the four values save. Does anyone know why this is?