- Home /
JS Wait for a function to complete - no WaitForSeconds
Hello,
There are number of threads on 'wait for function to finish or complete', allot of them either use wait for Seconds or number of frames or they are not appropriate to this problem.
I am look for a Javascript answer without the use of waitForSeconds(), instead it should just wait until all the commands inside a function are executed.
What I am trying to do:
OnMouseDown(){
1. rotate an object by 180 ( wait until object is completely rotated).
2. switch camera view.
}
My code :
function OnMouseDown(){
yield rotate(menuScreen,-180.0,true); // yield StartCoroutine(rotate(menuScreen,-180.0,true));
camOne.camera.enabled = true;
cameTwo.camera.enabled = false;
}
function rotate(gObj:GameObject, limit:float) {
var upperLimit = gObj.transform.rotation.y;
var lowerLimit = limit;
for(var i: float = upperLimit; i> lowerLimit; i-=0.1){
gObj.transform.rotation.y = i;
yield ;
}
}
Problem with current code : Function waits for object to rotate but it does not proceed further after completely rotating the object i.e. in this case camera does not switch.
Notes :
If I remove any 'yield', unity in a blink finishes the rotation and switch to another camera.
I believe, yield waits for single frame and that is fine in this case.
Thanks
Try using:
gObj.transform.eulerAngles.y
Ins$$anonymous$$d of:
gObj.transform.rotation.y
You may have to define the whole Vector3 though:
gObj.transform.eulerAngles = Vector3( gObj.transform.eulerAngles.x, i, gObj.transform.eulerAngles.z );
Answer by chayanvinayak · Mar 28, 2014 at 01:07 AM
thanks highPocket.
To explain what was happening:
When I used :
for(var i: float = upperLimit; i> lowerLimit; i-=0.1){
gObj.transform.rotation.y = i;
yield ;
}
At i = -1 , rotation of gObj became -180. Beyond -1, the object was not rotating (value of i was increasing slowly), but as it was not giving any visual change it appeared to be frozen.
Working Code :
function OnMouseDown(){
yield rotate(menuScreen,-180.0,true); // yield StartCoroutine(rotate(menuScreen,-180.0,true));
camOne.camera.enabled = true;
cameTwo.camera.enabled = false;
}
function rotate(gObj:GameObject, limit:float) {
var upperLimit = gObj.transform.eulerAngles.y;
var lowerLimit = limit;
for(var i: float = upperLimit; i> lowerLimit; i-=0.1){
gObj.transform.eulerAngles = Vector3( gObj.transform.eulerAngles.x, i, gObj.transform.eulerAngles.z );
yield ;
}
}
Your answer
Follow this Question
Related Questions
How To Create Coroutine Delegates? 1 Answer
Yield position within while loop in coroutine 1 Answer
Coroutines and states 1 Answer
StartCoroutine important for using yield? 1 Answer
Fire and forget coroutines 1 Answer