- Home /
Wait for a second without using Coroutine
Hello! I am trying to make a script that allows the player to take a screen shot, then notifies them of it. I have created this script here:
using UnityEngine; using System.Collections; using UnityEngine.UI;
public class ScreenShotScript : MonoBehaviour {
public Text screenshotText;
public float textShow = 10f;
void Start () {
screenshotText.enabled = false;
}
void Update () {
if(Input.GetButtonDown("Screenshot")) {
ScreenShot();
}
}
void ScreenShot() {
Application.CaptureScreenshot ("Screenshot.png");
screenshotText.enabled = true;
//Right here is where it would wait for 10 seconds
screenshotText.enabled = false;
}
}
The problem is, whenever I try to make it wait so then the players sees the message then it disappears, I get an error trying to use corountine. Is there anyone who can help me? Thanks!
Answer by TwinGhosts · Aug 11, 2017 at 08:00 PM
You need to use an IEnumerator for a coroutine. After that you can use a new yield waitforseconds. This is how the manual handles it.
using UnityEngine;
using System.Collections;
public class WaitForSecondsExample : MonoBehaviour
{
void Start()
{
// Start the coroutine - enter the name of the IEnumerator
StartCoroutine(Example());
}
IEnumerator Example()
{
// Code before the pause
yield return new WaitForSeconds( 5 ); // Wait or a number of seconds
// Code after the pause
}
}
Alternatively, you could use Invoke to wait a couple of seconds before calling a Method.
void Start(){
Invoke("Screenshot", 5f); // Name of the method and time before it calls
}
void Screenshot(){
// Your code which gets called after 5 minutes
}
Answer by unity_niWqoFh70ON5rg · Mar 18, 2020 at 10:56 AM
Does this work ?
public float wait; private float waitTime;
void Update() { waitTime = Time.time + wait; while (Time.time < waitTime) {} }
No, it does not. Time.time can only change between two frames. This is true for almost all frame dependent data. Even if it would work your application would be locked up during that times. $$anonymous$$ost operating system would report such an application as "not responsive" and might kill / offer to kill it.
What you've posted is not an answer but a question. Next time when you want to ask a question, please Ask a Question ins$$anonymous$$d of writing an Answer.