Question by
BenediktFisch · May 17, 2016 at 03:37 PM ·
script.fixedupdatetime.time
How can i change a value for a specific amount of time?
I want to change my characters speed to a higher value a soon as the player presses space. But only for a specific amount of time. Heres the code: (Its a 2D game btw)
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
private float characterSpeed = 0.10f;
private float rollTime = 0.25f;
void FixedUpdate()
{
if (Input.GetKey(KeyCode.W))
{
transform.Translate(Vector2.up * characterSpeed);
}
if (Input.GetKey(KeyCode.A))
{
transform.Translate(Vector2.left * characterSpeed);
}
if (Input.GetKey(KeyCode.S))
{
transform.Translate(Vector2.down * characterSpeed);
}
if (Input.GetKey(KeyCode.D))
{
transform.Translate(Vector2.right * characterSpeed);
}
if (Input.GetKey(KeyCode.LeftShift))
{
characterSpeed = 0.2f;
} else {
characterSpeed = 0.10f;
}
Roll();
}
void Roll()
{
if (Input.GetKeyDown(KeyCode.Space))
{
while (Time.time < Time.time + rollTime)
{
characterSpeed = 0.30f;
}
characterSpeed = 0.10f;
}
}
}
But every time i try it Unity just freezes and i just cant find the mistake in the code.
Comment
$$anonymous$$aybe because you make an infinite loop in the Roll function ? In Unity, a while doesn't wait for a new frame after each iteration....
Use Coroutines for this
This is the correct diagnosis, you can't expect the Time.time value to change from within that scope during while execution.
Answer by Jessespike · May 17, 2016 at 09:28 PM
float rollEndTime;
void Roll()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rollEndTime = Time.time + rollTime;
}
if (Time.time < rollEndTime)
{
characterSpeed = 0.30f;
}
else
{
characterSpeed = 0.10f;
}
}
You can use a coroutine instead as suggested in the comments, but IMO, a coroutine would be overkill for this.