- Home /
Bug? And any way to do something for 5 seconds when shift is held?
I need to setup a power up system so on shift down the rigid-body on the player will be disabled. Here is the code I have so far. The only problem with this code is when you hit shift in the game.... Frozen freezes up every time.
void Update ()
{
PowerupTimer = Time.realtimeSinceStartup;
PowerupTimer2 = Time.realtimeSinceStartup + 5;
if(Input.GetKeyDown(KeyCode.LeftShift) & PowerupUsed == false)
{
NoclipPowerup();
}
}
void InstantiatePlatforms()
{
while(NumberOfPlatforms > 0)
{
RandNum = Random.Range(0,PlatformList.Count); //Generates a random number from zero to the total amount of things in our list
Instantiate(Platform, PlatformList[RandNum].position, Quaternion.identity);
PlatformList.RemoveAt(RandNum); //Removes the transform contained at the index we picked at random. You don't want to reuse a spot, since that could put a platform on top of a platform.
NumberOfPlatforms = NumberOfPlatforms - 1;
}
}
void NoclipPowerup()
{
while(PowerupTimer < PowerupTimer2)
{
Debug.Log("The Powerup works");
}
}
Any ideas on the powerup and/or how to fix the crash?
Answer by iwaldrop · Apr 17, 2013 at 01:43 AM
It's not a bug, you need to use a Coroutine. What you're doing here is sending Unity into an infinite loop because Time.realtimeSinceStartup is always going to be less than Time.realtimeSinceStartup +5. :)
Try this:
if(Input.GetKeyDown(KeyCode.LeftShift) & PowerupUsed == false)
StartCoroutine(NoclipPowerup(5));
IEnumerator NoclipPowerup(float delay)
{
float startTime = Time.time;
collider.enabled = false;
while (startTime + delay > Time.time)
yield return null;
collider.enabled = true;
}
But, of course, you don't need to time it yourself, because Unity provides a mechanism for you; here's something a little more elegant.
IEnumerator NoclipPowerup(float delay)
{
collider.enabled = false;
yield return new WaitForSeconds(delay);
collider.enabled = true;
}
You should also consider putting some protection in there to ensure that you only call it once at a time.
Thanks a ton! Yea i just realized when viewing your comment that I was putting unity into a loop :P But thanks for the answer! Worked out great and the security check has been put in!
Your answer
![](https://koobas.hobune.stream/wayback/20220613100447im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Survival Timer 0 Answers
Trying to Create a Powerup that lasts a certain amount of time 1 Answer
magnetic Powerup Timer Problem 1 Answer
Timer not work :( 0 Answers
Timer running down too quickly 1 Answer