- Home /
Why does ScreenPointToRay bug when called from IEnumerators?
When calling screenPointToRay from within an IEnumerator I run across the following rather weird bug:
If I create the ray after calling a yield return new WaitForSeconds(..), the ray is not pointing where it's supposed to be. This problem doesn't occur with yield return new WaitForEndOfFrame().
For instance:
IEnumerator Demonstration() {
Vector3 mousePos = new Vector3 ( Input.mousePosition.x, Input.mousePosition.y, 0 );
Ray ray = Camera.mainCamera.ScreenPointToRay (mousePos);
Debug.DrawRay(ray.origin, ray.direction * 100, Color.red, 10 );
yield return new WaitForEndOfFrame();
ray = Camera.mainCamera.ScreenPointToRay (mousePos);
Debug.DrawRay(ray.origin, ray.direction * 100, Color.green, 10 );
yield return new WaitForSeconds ( 1.5f );
ray = Camera.mainCamera.ScreenPointToRay (mousePos);
Debug.DrawRay(ray.origin, ray.direction * 100, Color.yellow, 10 );
}
Produces the following (and this is a good case, sometimes the yellow ray is way off):
You can see that while the ray produced after WaitForEndOfFrame() is where it's supposed to be (green ray overlaps red), the ray produced after WaitForSeconds(..) (yellow) is not where it's supposed to be!
Any ideas why that is?
Answer by Anisoropos · Sep 02, 2013 at 02:53 PM
A dirty fix to this bug (if anyone happens to come across it) is to replace the WaitForSeconds(..) with multiple WaitForEndOfFrame() )
// Time we want to wait
float timeToWait = 1.5f;
// Replace this:
yield return new WaitForSeconds (timeToWait);
// With this:
float timer = timeToWait ;
while (timer > 0){
timer -= Time.deltaTime;
yield return new WaitForEndOfFrame ();
}
I've tested this and it works like a charm.
Your answer
Follow this Question
Related Questions
Why is the camera.screenpointtoray off? 1 Answer
Follow mouse cursor (with Y = 0)? 1 Answer
camera.ScreenPointToRay always has same origin... 1 Answer
Get 2D Collider with 3D Ray 2 Answers
Why won't my Ray initialization work?? 2 Answers