Unity 之 使用定时调用与Update 正常帧更新的运行答疑

在这里插入图片描述

疑惑

就是说,当我们在Start 函数里面定义了一个InvokeRepeating 函数,那么我们又在Update 定义了一个基本操作,想联合控制物体一个往返的一个运动时,我们应该怎么办?
就是说系统是怎么编译的呢?

代码辨析

这里我提供两个代码,大家看一下区别

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

public class SimpleLogic : MonoBehaviour
{
    public float speed = 1f;

    // Start is called before the first frame update
    void Start()
    {
        InvokeRepeating("DoSomesing", 2,2);
    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log("***this is Update ***" + Time.time);

        transform.Translate(0, speed * Time.deltaTime, 0, Space.Self);
    }
    void DoSomesing()
    {
        Debug.Log("***use Dosing ***"+ Time.time);
        //transform.Translate(0, -1*speed * Time.deltaTime, 0, Space.Self);
        speed = 0 - speed;
    }
}


另一个代码和它非常像

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

public class SimpleLogic : MonoBehaviour
{
public float speed = 1f;

// Start is called before the first frame update
void Start()
{
    InvokeRepeating("DoSomesing", 2,2);
}

// Update is called once per frame
void Update()
{
    Debug.Log("***this is Update ***" + Time.time);

    transform.Translate(0, speed * Time.deltaTime, 0, Space.Self);
}
void DoSomesing()
{
    Debug.Log("***use Dosing ***"+ Time.time);
    transform.Translate(0, -1*speed * Time.deltaTime, 0, Space.Self);
    //speed = 0 - speed;
}

}

这两个代码就是一行的差别,那么你知道哪一个可以真正实现往返运动吗?

其实第一个代码正确

具体解释

在这里插入图片描述

就是说我们的Update 是每一帧都运行,而InvokeRepeating 只有特定的时间才运行,那么我们把控制物体运行的关键点速度就只能放在InvokeRepeating 里面了,而对于控制前进的代码就应该放在Update 中,毕竟每一帧都要前进的!

猜你喜欢

转载自blog.csdn.net/weixin_74850661/article/details/132773501