Need help!!
I want to insert PlayerPrefs script in the below code to save the timer even after switching between scenes or closing the application.
When I hit the button the button disappears and cooldown timer gets started, but when I switch between scenes or restarting the application, the button gets appeared.
I need help to insert PlayerPrefs code in the below script.
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class ButtonCooldown : MonoBehaviour
{
[SerializeField]
Button myButton;
[SerializeField]
float cooldownDuration = 60f;
void Awake()
{
myButton = GetComponent<Button>();
if (myButton != null)
{
myButton.onClick.AddListener(OnButtonClick);
}
}
void OnButtonClick()
{
StartCoroutine(Cooldown());
}
IEnumerator Cooldown()
{
myButton.interactable = false;
yield return new WaitForSeconds(cooldownDuration);
myButton.interactable = true;
}
}
If you need this to persist from run to run, you can’t just use the WaitForSeconds construct.
Here is how you check / compare times and dates:
Get that fundamentally working so that it calculates a value from the base time, a value that you can recalculate on load and give to your wait for seconds delay. (without saving to PlayerPrefs yet!) Just understand it and get comfortable with it.
Once you have that working, then you can simply store the start time obtained above into PlayerPrefs with this call:
And when you come back load it with GetString(), then do the above calculations on the saved value.
Alternatively you can track your own “seconds counter” for example, and on application exit write it out to PlayerPrefs with the same calls above. But it will not advance in time unless you involve System.DateTime, which ties into the computer’s clock.
@Kurt-Dekker
Thanks for the suggestion.
Here is my code updated. Still its not working as expected. Can you rewrite the code? I’m not good at coding.
I don’t think this is right code. coz I want set time like 10mins cooldown.
Is it possible to call API from time server?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class ButtonTimer : MonoBehaviour
{
[SerializeField]
Button myButton;
void Awake()
{
myButton = GetComponent<Button>();
if (myButton != null)
{
myButton.onClick.AddListener(OnButtonClick);
PlayerPrefs.GetString("date_time");
myButton.interactable = true;
}
}
void OnButtonClick()
{
PlayerPrefs.SetString("date_time", System.DateTime.Now.ToString("HH:mm:ss"));
myButton.interactable = false;
}
No sir, that’s VERY expensive and that’s not what this forum is for. This is for YOU to write the code, debug it, and report specific problems.
If the above code is having a specific problem, this will help you:
How to report problems productively in the Unity3D forums:
http://plbm.com/?p=220