I want to create a c# script that will activate a button automatically after a certain amount of time. But after you press it it will diactivate the button automatically again nad wait until the time passed again.
Thank you in advance.
This is a generic script to add a timer to anything, you can add this to any gameObject
Just set the timeToWait in the inspector. Add your own code to TimerFinished. The Public Function ResetTimer is there to startt the timer again if needed.
public class WaitTimer : MonoBehaviour
{
public float timeToWait;
private currentWaitTime;
private bool checkTime;
void Awake()
{
ResetTimer();
}
void Update()
{
if (checkTime)
{
currentWaitTime -= Time.deltaTime;
if (currentWaitTime < 0)
{
TimerFinished();
checkTime = false;
}
}
}
public void ResetTimer()
{
currentWaitTime = timeToWait;
checkTime = true;
}
void TimerFinished()
{
// Add Code here for timer finishing
// Like activating a button
}
}
It says that currentWaitTime does not exist in your project. what should i do?
Couldn’t you do this with a coroutine as well?
void Start()
{
StartCoroutine(ButtonCoroutine());
}
IEnumerator ButtonCoroutine()
{
yield return new WaitForSeconds(3f);
// Turn on the button & make it active
}
Something along these lines?
This is the simplest way in my opinion. You also don’t need that final “yield return null”. As long as the code will hit at least one yield statement the coroutine is valid.
If you throw CallLater.cs into your project, then you could do it this way:
CallLater.DoAfter(3, x => {
myButton.SetActive(true); // or whatever you want to do
});
The “3” above means 3 seconds; obviously change that to whatever you like, and put whatever code you need to enable the button in place of line 2.
Edited my answer to remove it, thanks. I’m still new so wasn’t sure - just based it off an example I had seen in the docs the other day. Good tip!