2015-02-05 68 views
0

我正在制作和游戏,因为它的功能,所以我需要计时器,它会计算确切的浮点数(以秒为单位),然后销毁gameObject。这是我现在尝试的,但它是冷冻的统一:挖掘技术计数器

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); 
        } 
     } 

回答

1

这是一个基本的例子想法如何检查玩家是否点击了某段时间。

#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上设置为true,在GetMouseButtonUp上设置为false。

0

更新函数每帧被调用。如果你在这个函数内添加一个while循环来等待mouseButtonUp,你肯定会冻结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; 
     } 
    } 
} 

未成年人控制应该被添加到避免破坏游戏物体几次,但这是前进

+0

好的,但那不是我想要的。我想让玩家挖掘,而他们正在举行左键点击。如果我检查MouseButtonUp是否为真,我强制玩家释放点击,以便他可以挖掘出他想要的东西?!我该如何实现这样的功能:在按住左键启动计时器的同时,如果计时器结束并且点击尚未释放,请销毁该对象? – 2015-02-05 21:48:38

+0

我刚刚编辑我的答案与posible解决方案的例子 – 2015-02-06 08:30:32