- Home /
WaitUntil Combined With sqrMagnitude is not working?
Hello,
Have a bit of code that I want to wait to execute until a certain Distance between the player and an object is true. I use a RaycastHit to get the other object position.
Here are two versions. The first one works with Vector3.Distance. But I have read that Vector3.Distance is much slower so I am trying to optimize the code with sqrMagnitude.
Working Version:
yield return new WaitUntil(() => Vector3.Distance( thisTransform.position, hit.transform.position) < 0.0125);
Non-Working Version with SqrMagnitue:
float closeDistance = 0.125f;
float sqrLen = (hit.transform.position - thisTransform.position).sqrMagnitude;
yield return new WaitUntil(() => (sqrLen < closeDistance * closeDistance));
I have experimented with the float closeDistance. If I increase it to 0.6 it works. But I want the objects to be closer (almost equal) until it executes.
I believe the problem is that sqrMagnitude is only being execute once and not being updated to work together with waitUntil.
Any Suggestions on how to set it up would be appreciated.
Thanks, Raymond
Answer by r_chevallier · Mar 31, 2018 at 04:49 PM
Figured out the answer 10 minutes after I posted.
I put the sqrMagnitude code directly into the WaitUntil so it would update.
yield return new WaitUntil(() => (hit.transform.position - thisTransform.position).sqrMagnitude < 0.0005);
If anyone has a better way to do this I still would like to here suggestions.
Thanks, Raymond
Your answer
Follow this Question
Related Questions
Best way to wait for event inside Coroutine? 3 Answers
Waiting for input using yield and coroutines 1 Answer
Alternative for semaphores in Unity? 2 Answers
C# Coroutine help 1 Answer
Wierd issue with Coroutines? 2 Answers