I have been trying to make a series of Lerp move functions work one after the other for an intro to my simple racing game. (Camera starts in some place moves a bit then teleports to some other place moves a bit and so on). The way I have been tackling this problem is with the following code:
using UnityEngine;
using System.Collections;
public class PreviewCamera : MonoBehaviour {
public Transform[] cameraPos;
public bool finished = false;
public float fraction = 0;
public float speed = 0.2f;
//Fill the array with the caamera positions for the race preview
void Start () {
//Fill the array (indexes 0 and 1 will be useless)
cameraPos = transform.parent.GetComponentsInChildren<Transform>();
//Set first camera at position 2
transform.position = cameraPos[2].position;
transform.rotation = cameraPos[2].rotation;
StartCoroutine(RunPreviewCamera());
}
// Update is called once per frame
void Update () {
if (fraction <= 1)
{
fraction += Time.deltaTime * speed;
}
}
IEnumerator RunPreviewCamera()
{
StartCoroutine(MoveCamera(transform, cameraPos[3]));
yield return null;
}
//Function to teleport camera from one position to another
void TeleportCamera( Transform teleportPos)
{
transform.position = teleportPos.position;
transform.rotation = teleportPos.rotation;
}
//Function to move camera from current position to another
IEnumerator MoveCamera(Transform fromPos, Transform movePos)
{
fraction = 0;
while(fraction < 1)
{
transform.position = Vector3.Slerp(fromPos.position, movePos.position, fraction);
transform.rotation = Quaternion.Slerp(fromPos.rotation, movePos.rotation, fraction);
}
yield return null;
}
}
What I supposed would happen is that since the fraction variable changes in the Update() eventually it would escape from the loop in the coroutine MoveCamera but it doesn’t and it crashes unity every time I run the game. I suppose update() is not being called if MoveCamera doesn’t finish? Is my way of thinking wrong? Any way to do it via scripting and not just making 4 different cameras in my scene and calll them to make the moves I want one by one?