- Home /
The question is answered, right answer was accepted
Why is it that when I pass this variable to an IEnumerator, it stops working?
These lines
Vector3 direction = Vector3.up / 4 + Vector3.left / 4;
transform.Translate (direction);
are changed to
Vector3 direction = Vector3.up / 4 + Vector3.left / 4;
StepUp (direction);
Currently.
In StepUp:
IEnumerator StepUp (Vector3 direction) {
yield return new WaitForSeconds (0.1f);
transform.Translate (direction);
}
Whole code:
void WalkUpBlocks () {
Bounds bounds = colliderRef.bounds;
RaycastHit2D hitLeft = Physics2D.Raycast (new Vector2 (bounds.min.x - 0.125f, bounds.min.y + 0.875f), Vector2.down, 0.75f, layerMask);
if (hitLeft == true)
{
if (hitLeft.distance == 0.625f)
{
if (Input.GetKey (KeyCode.A))
{
Vector3 direction = Vector3.up / 4 + Vector3.left / 4;
transform.Translate (direction);
}
}
}
RaycastHit2D hitRight = Physics2D.Raycast (new Vector2 (bounds.max.x + 0.125f, bounds.min.y + 0.875f), Vector2.down, 0.75f, layerMask);
if (hitRight == true)
{
if (hitRight.distance == 0.625f)
{
if (Input.GetKey (KeyCode.D))
{
Vector3 direction = Vector3.up / 4 + Vector3.right / 4;\
transform.Translate (direction);
}
}
}
}
public void CheckForGround (Vector3 velocity) {
for (int r = 0; r < rayCountY; r ++)
{
Vector2 rayOrigin = raycastOrigins.bottomLeft;
rayOrigin += Vector2.right * (spacingX * r + velocity.x);
RaycastHit2D groundCheck = Physics2D.Raycast (rayOrigin, Vector2.down, skinWidth, layerMask);
isJumping = !groundCheck;
}
}
Even if I make the method WalkUpBlocks an IEnumerator for simplicity's sake, it doesn't work. Basically I have a left raycast and a right. the right works correctly with coroutines, whereas left raycast stops working with coroutines. This could be that right raycasting comes after, but what is weird is that I Debugged everywhere, and the first place to go wrong is right at the beginning of the coroutine. It definitely is making it to the part where it calls the IEnumerator, but after it is in the coroutine it doesn't Debug?
Answer by zach-r-d · Jun 30, 2015 at 01:11 AM
Coroutines in C# must be started with StartCoroutine like so:
StartCoroutine(StepUp (direction));
Calling the method directly, without wrapping it in StartCoroutine or saving it to a variable to later be passed to StartCoroutine, will yield an IEumerator which is simply discarded. Since MoveNext is never called on the returned IEnumerator (under the hood, Unity calls MoveNext on IEnumerators when it is time for coroutines to resume), the yield return inside the function is never passed.
cant believe i missed that! sometimes we all need a second pair of eyes :)
Glad it worked out. Remember to accept answers if you feel your question has been answered; you gain reputation by doing so. :)