0
\$\begingroup\$

When I load my script, time starts from zero. How do I save my game timer?

Here is my script:

public float seconds, minutes, hours;
public Text levelTimer;
public float GameTime;

// Update is called once per frame
void Update () 
{
    hours = (int)(GameTime / 3600.0f);
    minutes = (int)(GameTime / 60f);
    seconds = (int)(GameTime % 60f);

    levelTimer.text = hours.ToString("00") + ":" +
            minutes.ToString("00") + ":" + seconds.ToString("00");
    GameTime += Time.deltaTime;
}

public void save()
{
    PlayerPrefs.SetFloat("second1",seconds);
    PlayerPrefs.SetFloat("mins1",minutes);
    PlayerPrefs.SetFloat("hour1",hours);
}

public void load()
{
    seconds = PlayerPrefs.GetFloat("second1");
    minutes = PlayerPrefs.GetFloat("mins1");
    hours = PlayerPrefs.GetFloat("hour1");
}
\$\endgroup\$
  • \$\begingroup\$ Are you calling load and save at any point? \$\endgroup\$ – Daniel Oct 30 '16 at 18:56
  • \$\begingroup\$ I press on save button to save my time example 01:30:40. When i press on load button it not load my save time. \$\endgroup\$ – user43474 Oct 30 '16 at 19:00
  • \$\begingroup\$ Downvoted for lack of grammatical coherence and the general absence of even the most elementary-level sentence structure. The question also shows no effort, nor provides enough information for an answer to be generated. \$\endgroup\$ – Krythic Oct 30 '16 at 20:53
  • 1
    \$\begingroup\$ @Krythic, you should remember that not all users come from English speaking backgrounds, and that many languages use a completely different structure to English. Applying that to this question, it makes perfect sense, to me. It was also answered well before your comments that it does not provide enough information for an answer. \$\endgroup\$ – Gnemlock Oct 31 '16 at 0:07
  • \$\begingroup\$ @Gnemlock This is an English speaking site. Your comment is invalidated. \$\endgroup\$ – Krythic Oct 31 '16 at 11:41
1
\$\begingroup\$

In the Update method, hours minutes and seconds are always getting updated with GameTime, so it won't get the saved preferences. On load, you should set your GameTime to seconds + minutes + hours or just save GameTime and use that.

Maybe it's worth that you check TimeSpan. It may help you with this timer and the way of represent it in a string.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.