【问题标题】:Unity create local variable for Time.DeltaTime for math calculationsUnity 为 Time.DeltaTime 创建局部变量以进行数学计算
【发布时间】:2021-11-12 19:24:32
【问题描述】:

我最近在思考如何以更好的方式编写代码。目前,我正在做数学calculations 并想知道是否应该将Time.deltaTime 缓存到一个自己的变量中以便同步。

float a = speed * Time.deltaTime;
float b = speed / Time.deltaTime;
float c = a - b;

或者

float deltaTime = Time.deltaTime;
float a = speed * deltaTime;
float b = speed / deltaTime;
float c = a - b;

这只是我编的随机代码,但重点是调用Time.deltaTime时调用的是内部更新。

    //
    // Summary:
    //     The interval in seconds from the last frame to the current one (Read Only).
    public static float deltaTime
    {
        [MethodImpl(MethodImplOptions.InternalCall)]
        get;
    }

意思是不同步,对吧?显然这是一件小事,但您仍然应该缓存 Time.deltaTime 以保持同步吗?

【问题讨论】:

  • 简单地说,你不会看到任何区别。好处是写起来更短,如果你在很多地方使用它,并且你决定用另一个值替换 Time.deltaTime,比如 Time.fixedDeltaTime,那么你就有一个地方可以改变,它会影响所有其他地方。在性能方面,您将节省一打滴答声,这基本上不算什么。
  • Meaning not in sync, right?, 错误.. 在整个帧中它将具有完全相同的值。

标签: c# unity3d synchronization execution


【解决方案1】:

Everts 是正确的,在大多数情况下它并不重要。 derHugo 可能是正确的,特别是在 Unity 中,这个值是每帧固定的。 但作为一项规则,好的编程不会留下任何机会,所以第二个版本会更正确。

float deltaTime = Time.deltaTime;
float a = speed * deltaTime;
float b = speed / deltaTime;
float c = a - b;

想象另一种情况,例如,我们使用日期。

// The value for the key. This will be either the existing value for the key if
// the key is already in the dictionary, or the new value if the key was not in
// the dictionary.
var dateTime = dictionary.GetOrAdd(key, value: DateTime.Now);           

// This will always be true because DateTime.Now returns different value
if (DateTime.Now != dateTime)
{
    // Compares the existing value for the specified key with a specified value, and 
    // if they are equal, updates the key with a third value.
    _exceptionContainer.TryUpdate(key, newValue: DateTime.Now, comparisionValue: dateTime);

    // We have updated key with different datetime value than compared earlier.
}

在上面代码的开头,我们应该写

var now = DateTime.Now;

并使用 now 变量代替 DateTime.Now

【讨论】:

  • 对于DateTime.Now,这很有意义,因为它每次都调用一个非常昂贵的类型的构造函数......你不能直接比较两者......Time.deltaTime是一个单一的浮动所以无论是再次使用它还是为其分配一些局部变量更有效,这几乎是一种微优化/非常取决于具体的用例;)有人需要对这些进行基准测试^^
  • 你写了一个我写的关于良好实践的具体案例。就我而言,无需怀疑它是否会起作用。在需要时进行优化,而不是过早地进行。
猜你喜欢
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-24
相关资源
最近更新 更多