I need help making a script where after 20 seconds have passed the application closes. Nothing else. Anyone know how to do that. Please give me the script. It shouldn’t be too hard I think.
void Start(){
StartCoroutine(CloseAfterTime(20));
}
public IEnumerator CloseAfterTime(float t){
yield return new WaitForSeconds(t);
Application.Quit();
}
Unless you are looking for a timeout feature? Where actions reset that 20 second timer, and you only want to close after 20 seconds of inaction?
PS code typed right into the browser - check for any possible compilation issues.
No, I just need it to wait 20 seconds, so this should work I think,
For some reason your script is not working. Are you sure you did it right? Am I doing anything wrong. I just need the game to wait 20 seconds and then it will close. Also the console say I doesn’t know what IEnumerator is?
Does anyone else know how to do this? Anyone???
You need to throw the code in a monobehavior script that is attached to some gameobject in the scene.
using System.Collections
Should be at the top, you need it to use IEnumerator, though it comes standard on a new C# script in unity.
Sorry I am I bit confused. So this is a C# script.
System.Collections
void Start(){
StartCoroutine(CloseAfterTime(20));
}
public IEnumerator CloseAfterTime(float t){
yield return new WaitForSeconds(t);
Application.Quit();
}
This is my C# script that I put in one of my objects in the game. It won’t work.
You should be creating a new C# script, which gives you a template monobehavior class named the same name as your script name. Start and Update should already be stubbed functions inside. Simply remove the Start and Update methods, put the code there inside that class, and it should compile. Then add that script as a component to an empty gameobject in your scene.
If you aren’t following what I am saying, Learn might be a useful link to check out. It sounds like you have very little experience with scripting in Unity, that would be a good place to get started. Even the very first scripting tutorial might be enough to teach you what you need to know for this.
Yeah, I am a bit lost, but I will go check out the learn page. Thanks so much for giving me a few tips on how to do this. ![]()
Finally got it, this is all it was,
yield WaitForSeconds (25);
Application.Quit();
Wow, I lost a lot of time trying to get that!!! LOL!
Thanks for the help!
Another noob here. Tried all the solutions suggested here. None give errors and allow me to run play mode, but also none lead to the quiting of the game after x seconds. Is Application.Quit() supposed to work in the Unity Game mode?
Or only when running a built game?
And can this code simply be attached to any Game Object? I am now attaching it to my FirstPersonCharacter. Any help very much appreciated!
Application.Quit will only work in a standalone build. It will be ignored in the Unity editor.
See: https://docs.unity3d.com/ScriptReference/Application.Quit.html
Yes.