0
\$\begingroup\$

I want to get rid of a co-routine and do this with a void.

How could I convert his IEnumerator into a void?

private IEnumerator pChangeFoV()
{
    float zValue =70f;

    for (float t = 0f; t < FoVDuration; t += Time.deltaTime)
    {
        float fNew = Mathf.Lerp(_camera.fieldOfView, zValue, t / FoVDuration);
        _camera.fieldOfView = fNew;
        yield return 0;
    }
    _camera.fieldOfView = zValue;
}

Thank you for the help!

\$\endgroup\$
2
\$\begingroup\$

Short answer:

private void pChangeFoV()
{
    float zValue =70f;

    for (float t = 0f; t < FoVDuration; t += Time.deltaTime)
    {
        float fNew = Mathf.Lerp(_camera.fieldOfView, zValue, t / FoVDuration);
        _camera.fieldOfView = fNew;
    }
    _camera.fieldOfView = zValue;
}

I just removed the yield keyword, since it is a special keyword that states that the statement, this case a method, is an iterator (IEnumerator, or T Generic IEnumerator).

Nonetheless, by turning it into void, you are losing the smooth FOV change you wanted to achieve. To turn the functionality into a void, I'd do something like this:

private bool smoothChange = true;
private float zValue = 70f;
private float t = 0.0f;

private void Update()
{
    if(smoothChange) pChangeFoV();
}

private void pChangeFoV()
{
    _camera.fieldOfView = Mathf.Lerp(_camera.fieldOfView, zValue, t);
    t += Time.deltaTime / FoVDuration;

    if(t >= 1.0f)
    {
        _camera.fieldOfView = zValue;
        smoothChange = false;
    }
}

Although I'd rather use coroutines for these kinds of functionalities.

\$\endgroup\$
  • \$\begingroup\$ Thank you, but isn't there a typo in your code? You are lerping from "_camera.fieldOfView" to "t". Is that correct?? I don't see how you take the target field-of-view "zValue" into account. If I am wrong, could you perhaps comment your code in order to explain what you're doing? \$\endgroup\$ – tmighty Feb 19 '19 at 19:08
  • 1
    \$\begingroup\$ Indeed, it was a typo, it is corrected already. Thanks \$\endgroup\$ – LifGwaethrakindo Feb 19 '19 at 19:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.