- Home /
Vector3.MoveTowards becomes instant in while loop or freezes unity
bool inputMove;
bool canReturn;
float mainSpeed = 16
void Update()
{
if (Input.anyKeyDown)
{
if (Input.GetKey(KeyCode.Escape))
{
// da
}
else
{
if (!inputMove)
{
inputMove = true;
}
}
}
while (inputMove)
{
print("inputMove = true");
float step = mainSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, new Vector3(0f, 2.4f, 0f), step);
if (transform.position == new Vector3(0f, 2.4f, 0f))
{
inputMove = false;
canReturn = true;
}
}
while (canReturn)
{
print("canReturn = true");
float step = mainSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, new Vector3(0f, 4.4f, 0f), step);
if (transform.position == new Vector3(0f, 4.4f, 0f))
{
canReturn = false;
}
}
}
at 16 and 1.6 for mainSpeed it just moves the game object instantly and when I try lower values for mainSpeed it starts freezes a bit and then the game object doesn't move and when I get to 0.016 and lower for mainSpeed unity freezes completely
Answer by BenWiller1989 · Sep 04, 2020 at 10:36 AM
Just replace your "while" statements with "if" statements! The problem you have is, that your script asks at least 60 times a second, to move an Object in a single frame to a specific location. So why not just assigning the location directly, if you really want that, instead of looping the hell out of it? If that's not what you want, just replace while with if and you're good. While loops are very mean, if you use them wrong, especially with wiggly float values. You have to match the exact float values in order to stop the loop. That's why it could freeze, if you miss them in a frame.
early I tried using ifs and maybe I messed something up and it only went down but now it works
Your answer
Follow this Question
Related Questions
Quaternion.Slerp issue 1 Answer
Iterator variable not increasing. 1 Answer
How to get something to be inactive while there is a certain value 2 Answers
Display a loading while processing a while loop 1 Answer
While loop freezes unity 3 Answers