Moh*_*han 3 c# unity-game-engine
我希望我的应用程序在第一次按下后退按钮时将消息显示为“请再次触摸后退按钮以退出应用程序”,当再次按下时,应用程序应退出。我想我已经添加了适当的代码,但它不起作用。
该脚本作为组件附加到画布元素。该脚本包含我分配给面板(画布的子级)UI 元素的公共变量。
观察到: 当我按下后退按钮时,文本出现但只有几分之一秒,然后突然消失,下一次后退按钮按下并没有导致应用程序退出。
Desired 在第一个后退按钮按下它应该显示消息,如果第二个后退按钮按下应用程序应该在 3 秒内退出。
相关资料: Unity 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);
}
}
Run Code Online (Sandbox Code Playgroud)
我见过几个例子,其中Application.Quit();并没有在Android上工作。发生这种情况时,请使用System.Diagnostics.Process.GetCurrentProcess().Kill();退出程序。
现在,对于您的计时器问题,请Update在第一次按下输入时在函数中启动协程。使用标志确保在最后一个协程函数完成之前不会再次启动此协程函数。布尔变量很好。
内饰方面,该协程的功能,不使用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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3438 次 |
| 最近记录: |