首页 > 解决方案 > 区域周围经过的记录时间(统一)

问题描述

我是统一的新手,想创建一个具有可移动对象和显示网格的场景。当对象移动到网格区域时,我希望它记录在网格上花费的时间,一旦它离开指定的网格区域,我想接收它在网格上花费的时间。我曾尝试使用此代码。

if (collision.gameObject.name == "GridHolder")
{
    stopwatch.Start();
    isInSection1 = true;
    isInSection2 = false;
    Debug.Log("In area");
    if (!(collision.gameObject.name == "GridHolder"))
    {
        stopwatch.Stop();
        Debug.Log("Left area");
        Debug.LogFormat("Time elapsed: {0}", stopwatch.Elapsed);

    }
}

我已经尝试过了,它不会显示时间。我测试了它是否在第一个 if 语句中使用 time elapsed 语句记录时间。它确实记录了时间,并在我将对象带回该区域时继续记录和消逝的时间。

标签: c#unity3dtimer

解决方案


秒表功能不会暂停您的代码/等待,因此您检查剩下的游戏对象是否永远不会运行,因为 if 语句只能在您的第一个 if 语句运行时运行(基本上它总是错误的)。

if(collision.gameObject.name == "GridHolder"){
    if (!(collision.gameObject.name == "GridHolder")){
        //This if statement will never run, as the previous if statement contradicts this one.
}

您应该使用OnTriggerEnterOnTriggerExit来启动和停止秒表。


推荐阅读