I have a problem. I assigned the R key to restart the game with a single press. However, if I hold the key Unity keeps reloading the scene over and over until I release the key.
As you can see, I used GetKeyDown() not GetKey() so it's supposed to restart once for each press. Thanks.
Answer by allenallenallen
6 days ago
I'm not too sure about this but this is my theory.
When the scene reloads, it potentially resets all the info stored about your key presses. So right after it was first reloaded, it thinks that you are pressing the key down for the first time. So it reloads the scene again. And again and again in a loop.
Try using GetKeyUp() instead. That should work.
If you must use GetKeyDown, then you might consider using DontDestroyOnLoad for the GameObject that has the reload script. This way, it will persist and not think you press the key for the first time after the scene reloads.
Answer by Joe-Censored
6 days ago
I agree with allen that it is problably reloading the scene and then seeing the R still held down as a new key press, since this is the first frame this scene it has seen it.
How I might resolve it would be to prevent R from doing anything until the scene has been running for an arbitrary amount of time. Why would a player reload the scene within seconds anyway?
top of the script:
private float timeToWaitForR = 20f;
private bool enableR = false;
private float timeWaitedFromStart = 0f;
Replacing your code:
timeWaitedFromStart += Time.deltaTime;
if (timeWaitedFromStart >= timeToWaitForR)
enableR = true;
Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.
The best place to ask and answer questions about development with Unity.
To help users navigate the site we have posted a site navigation guide.
If you are a new user to Unity Answers, check out our FAQ for more information.
Make sure to check out our Knowledge Base for commonly asked Unity questions.
If you are a moderator, see our Moderator Guidelines page.
We are making improvements to UA, see the list of changes.
Answers and Comments
8 People are following this question.
Multiple Cars not working
Distribute terrain in zones
How to check whether you have swiped upwards on a mobile device - c#
GetKeyDown is not working
[C#] Unity asks for a } for a reason I don't know ( '}' expected )