挖掘技术计数器

Digging technique counter

我正在制作具有挖掘功能的游戏,所以我需要计时器来计算精确的浮点数(以秒为单位),然后销毁游戏对象。这是我现在尝试的方法,但它是冻结的统一:

function Update()
{

if (Input.GetMouseButtonDown(0))
{
                        digTime = 1.5; // in secounds
                  }
                  while (!Input.GetMouseButtonUp(0)) // why is this infinite loop?
                  {               
                  digtime -= Time.deltaTime;
                  if (digtime <= 0)
                  {
                  Destroy(hit.collider.gameObject);
                  }
        }

每帧都会调用更新函数。如果您在此函数中添加一个等待 mouseButtonUp 的 while 循环,您肯定会冻结 Unity。

您不需要 while 循环。只需检查没有 while 循环的 GetMouseButtonUp。

编辑

这是更新函数:

void Update ()
{
    if ( Input.GetMouseButtonDown( 0 ) )
    {
        digTime = 1.5f;
    }
    else if ( Input.GetMouseButton( 0 ) )
    {
        if ( digTime <= 0 )
        {
            Destroy( hit.collider.gameObject );
        }
        else
        {
            digTime -= Time.deltaTime;
        }
    }
}

应添加次要控件以避免多次破坏游戏对象,但这是继续进行的想法

这是一个基本示例,您可以如何检查玩家是否在特定时间段内点击过。

#pragma strict

// This can be set in the editor
var DiggingTime = 1.5;

// Time when last digging started
private var diggingStarted = 0.0f;

function Update () {
    // On every update were the button is not pressed reset the timer
    if (!Input.GetMouseButton(0))
    {
        diggingStarted = Time.timeSinceLevelLoad;
    }

    // Check if the DiggingTime has passed from last setting of the timer
    if (diggingStarted + DiggingTime < Time.timeSinceLevelLoad)
    {
        // Do the digging things here
        Debug.Log("Digging time passed");

        // Reset the timer
        diggingStarted = Time.timeSinceLevelLoad;
    }
}

即使玩家按住按钮,它也会每隔 DiggingTime 秒发射一次。如果您希望玩家需要松开按钮并再次按下,一种解决方案是添加布尔值来判断计时器是否开启。它可以在 GetMouseButtonDown 上设置为真,在 GetMouseButtonUp 上设置为假。