I am trying to set up a UI button that, when the user clicks it, it calls to a camera manager that will either lerp from one camera object to another, fade-in/fade-out to another camera object, or just snap to another camera object. The problem I am having is that the co-routine I am calling when the button is clicked does not seem to wait() and allow the lerp to finish. The camera moves a bit when I click but it seems to get interrupted, which is what I thought the co-routine yield would prevent. This is the OnGUI() function code that is in my HUD_mgr script:
void OnGUI(){
if(!next_Btn){
Debug.LogError("Please assign a texture on the inspector");
return;
}
if(GUI.Button(new Rect(10,10,50,50), next_Btn))
{
Debug.Log("Clicked the button. Yippee...");
camera_Mgr.SendMessage("switchCamera");
}
}
and here is the switchCamera() function code that is within my Camera_mgr script:
IEnumerator switchCamera(){
var duration = Time.deltaTime*3;
Vector3 pos = main_Camera.transform.position;
Quaternion rot = main_Camera.transform.rotation;
main_Camera.transform.position = Vector3.Lerp(pos, second_Camera.transform.position, duration);
main_Camera.transform.rotation = Quaternion.Lerp(rot, second_Camera.transform.rotation, duration);
yield return new WaitForSeconds(duration);
}
I am guessing that the fact that OnGUI() is called several times a frame is what is stomping my camera lerp just after it starts. However, if the yield does not work then what should I do? FYI, the snap-to works just fine. It’s the lerp and fade-in/fade-out that do not seem to complete properly.