我希望我的应用程序在第一次按下后退按钮时显示消息“请再次触摸后退按钮以退出应用程序”,再次按下时应用程序应该退出。我想我已经添加了适当的代码,但它不起作用。
脚本作为组件附加到 Canvas 元素。 该脚本包含我分配给面板( Canvas 的子项)UI 元素的公共(public)变量。
观察到: 当我按下后退按钮时,文本出现但只有几分之一秒,然后突然消失,下一次按下后退按钮并没有导致应用程序退出。
需要 在第一次按下后退按钮时,它应该显示消息,如果按下第二个后退按钮,应用程序应该在 3 秒内退出。
相关信息: 统一 2017.1.0f3
这是代码链接:
https://gist.github.com/bmohanrajbit27/431221fc80e0b247649289fd136f9cfb
public class ChangeSceneScript : MonoBehaviour
{
private bool iQuit = false;
public GameObject quitobject;
void Update()
{
if (iQuit == true)
{
if (Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
}
if (Input.GetKeyDown(KeyCode.Escape))
{
quitobject.SetActive(true);
iQuit = true;
StartCoroutine(QuitingTimer());
}
}
IEnumerator QuitingTimer()
{
yield return new WaitForSeconds(3);
iQuit = false;
quitobject.SetActive(false);
}
}
最佳答案
我见过一些 instances 的 Application.Quit();
在 Android 上不工作。发生这种情况时,使用 System.Diagnostics.Process.GetCurrentProcess().Kill();
退出程序。
现在,对于您的计时器问题,在第一次按下输入时在 Update
函数中启动协程。使用一个标志来确保这个协程函数在最后一个完成之前不会再次启动。 bool 变量就可以了。
在协程函数内部,不要使用yield return new WaitForSeconds(3);
来等待计时器。结合使用 while
循环和 yield return null;
等待计时器完成。每帧用 Time.deltaTime
增加计时器。现在,您可以轻松地检查该协程函数中的第二次按下并在按下时退出。
如果您还希望它在编辑器中工作,则必须使用 UnityEditor.EditorApplication.isPlaying = false;
退出。下面的示例也应该在编辑器中工作。如果您有任何问题,请参阅代码中的注释。
public GameObject quitobject;
private bool clickedBefore = false;
void Update()
{
//Check input for the first time
if (Input.GetKeyDown(KeyCode.Escape) && !clickedBefore)
{
Debug.Log("Back Button pressed for the first time");
//Set to false so that this input is not checked again. It will be checked in the coroutine function instead
clickedBefore = true;
//Activate Quit Object
quitobject.SetActive(true);
//Start quit timer
StartCoroutine(quitingTimer());
}
}
IEnumerator quitingTimer()
{
//Wait for a frame so that Input.GetKeyDown is no longer true
yield return null;
//3 seconds timer
const float timerTime = 3f;
float counter = 0;
while (counter < timerTime)
{
//Increment counter while it is < timer time(3)
counter += Time.deltaTime;
//Check if Input is pressed again while timer is running then quit/exit if is
if (Input.GetKeyDown(KeyCode.Escape))
{
Debug.Log("Back Button pressed for the second time. EXITING.....");
Quit();
}
//Wait for a frame so that Unity does not freeze
yield return null;
}
Debug.Log("Timer finished...Back Button was NOT pressed for the second time within: '" + timerTime + "' seconds");
//Timer has finished and NO QUIT(NO second press) so deactivate
quitobject.SetActive(false);
//Reset clickedBefore so that Input can be checked again in the Update function
clickedBefore = false;
}
void Quit()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
//Application.Quit();
System.Diagnostics.Process.GetCurrentProcess().Kill();
#endif
}
关于c# - 按 2 次后退按钮退出 Unity3D Android 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46109693/