如何使用StartCoroutine在7秒钟内将变量值从300递增到0,再递增1?

时间:2018-07-08 20:13:54

标签: c# unity3d

focusLength的值从300开始。 我想在7秒内将其递增1到0。 但是我的计算是错误的。增量花费的时间比7秒要多得多。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.PostProcessing;

public class DOFControl : MonoBehaviour
{
    public PostProcessingProfile postProcProf;

    public Animator anim;
    private float clipLength;

    private void Start()
    {
        AnimationClip[] clips = anim.runtimeAnimatorController.animationClips;
        foreach (AnimationClip clip in clips)
        {
            clipLength = clip.length;
        }

        StartCoroutine(incrementSpeed());
    }

    IEnumerator incrementSpeed()
    {
        while (true)
        {
            var dof = postProcProf.depthOfField.settings;
            dof.focalLength -= 1f;
            if (dof.focalLength == 0)
                break;
            postProcProf.depthOfField.settings = dof;

            yield return new WaitForSeconds(0.023f);
        }
    }
}

1 个答案:

答案 0 :(得分:3)

要@elgonzo对您的帖子的评论,它可能有助于您了解如何使用signUp。具体来说(来自API Documentation here):
a)它随log 2而变化。请确认这不是您的罪魁祸首。
b)在同一页面上,

  

注意:有一些因素可能意味着实际等待的时间与指定的时间不完全匹配。

这是合理的。引擎只能检查您设置的持续时间是否过去。该代码不能明确地强制引擎(以及控制操作系统本身)在准确的时间点运行代码。

这使您只能控制:
a)在运行代码之前,您大约要等待多长时间(或者使用稍微不同的方法,确切地说是多少帧);和
b)您的值每帧变化了多少。

(我对那里的null声明也有些担心。希望您理解它的风险。)

这里有一些快速的伪代码,可以帮助您找到所需的内容:

WaitForSeconds

我希望能有所帮助。祝你好运!