2015-02-05 117 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