- Home /
Coroutine not working properly
I wrote a simple coroutine that increases the character speed for half a second (FYI Creating the illusion of a dogde). This is the code
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public float characterSpeed = 0.10F;
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;
}
if (Input.GetKeyDown(KeyCode.Space))
{
StartCoroutine("Roll");
}
}
IEnumerator Roll()
{
characterSpeed = 0.20f;
yield return new WaitForSeconds(0.5f);
characterSpeed = 0.10f;
}
}
The Coroutine is called "Roll" and as far as i know everything is correct. I used the Unity Manual. Now everytime i press space character Speed increases. But only for 1 or so frame (Used the Console to read the value). Why is that so?
Answer by FortisVenaliter · May 20, 2016 at 06:27 PM
FixedUpdate is called every frame. And every frame, you have this code:
if (Input.GetKey(KeyCode.LeftShift))
{
characterSpeed = 0.2F;
} else {
characterSpeed = 0.10F;
}
...which resets the speed to 0.1 if left shift is not held down.
So is have to disable that code. I already wanted to lock the controls so the dodge has to be completed before the player can do anything.
Pretty much, yeah. $$anonymous$$aybe have a bool isDodging that gets set to true at the start, then false after the WaitForSeconds, and disable the rest if it's true.
I´ve done as you said and it works just perfectly. Thank you very much!
Your answer
Follow this Question
Related Questions
How to make object bounce from one bound to another? 0 Answers
Rigidbody2d not falling once in the air 1 Answer
2D walls affect my jump height 1 Answer
Cannot set motor speed in script 1 Answer
One-way physics reaction : Objects reacting with physics to player without player being affected 2 Answers