'Unity - Debug.DrawRay keeps drawing lines on every Update call

I have a skeleton game object which I make move by increasing its velocity on the Update function, like this:

body.velocity = new Vector2((isFacingLeft ? -1 : 1) * speed, body.velocity.y);

Which is also controlled by a direction isFacingLeft, which determines movement for the skeleton from left to right.

int direction = isFacingLeft ? -1 : 1;

But, since my skeleton is in a platform, I want to use a ray cast to ensure I detect whenever no platform is in front (so the cast points diagonally down in front of the skeleton), so I prepare a few variables to ensure I have a proper position for the ray cast. Then, if no floor has been found, the isFacingLeft variable is flipped, so the skeleton moves in the opposite direction as it approaches an edge:

 Vector2 beginFloorCast = new Vector2(transform.position.x + ((enemyWidth / 2) * direction), transform.position.y - enemyHeight / 2);
 Vector2 floorCastDirection = transform.TransformDirection(new Vector2(1 * (direction), -1));
 float floorCastLength = 1f;

 RaycastHit2D hit = Physics2D.Raycast(beginFloorCast, floorCastDirection, floorCastLength);

 if (!hit) {
   isFacingLeft = !isFacingLeft;
 }

While this all works, I am now trying to draw a debug ray so I can visualize in debug mode how long the floor ray is (and so I can use this in the future to detect if the player is in range of the skeleton with another ray), so I use the following:

Debug.DrawRay(beginFloorCast, floorCastDirection.normalized * floorCastLength, Color.green, 5f);

This also works, but in the Scene mode, the ray is drawn once for every Update call:

enter image description here

Is there a way for me to clear the debug screen after the Update function is done? Or what could I change in my code to make sure I only call it once and that the ray follows the skeleton?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source