2017-03-03 39 views
1

我目前正在編寫一個統一的c#腳本,主要思想是當我點擊模型的某個部分時,該部分將被突出顯示,現在我希望它返回通過再次點擊它到原始狀態。當我第三次點擊同一部分時,應該再次突出顯示。如何獲得統一的點擊次數c#

我不知道如何去實現它裏面Update()方法,因爲每次點擊費用幾幀,我不能承認這架是第2點擊,點擊3次,等

有什麼辦法在不考慮統一幀的情況下識別點擊次數?

void Update(){ 
    if (Input.GetMouseButton(0)) 
    { 
     RaycastHit hit; 

     if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit)){ 
       bone = hit.collider.transform; 
       if (boneList.Contains(bone) != true) 
       { 
        /* if the part is not chosen before, add it to the list and highlight all elements in the list */ 
        boneList.Add(bone); 
        Highlight(boneList); 
       }/*cannot delete the element chosen repetitively*/ 
    } 
}} 
+1

聽起來像你想'Input.GetMouseButtonDown()'(或'Input.GetMouseButtonUp()')而不是'Input.GetMouseButton()'? – Serlite

+0

@ squill25這很好,程序員的答案看起來比我現在能夠回答的時間要綜合得多。只要問題得到解決。 = P – Serlite

回答

4

你太親近了。應將else聲明添加到您的代碼中。你的邏輯應該是這樣的:

if(List contains clickedObject){ 
    Remove clickedObject from List 
    UnHighlight the clickedObject 
}else{ 
    Add clickedObject to List 
    Highlight the clickedObject 
} 

此外,像提到Serlite,你必須使用GetMouseButtonDown而不是GetMouseButton因爲GetMouseButtonDown當按下鍵,但GetMouseButton被稱爲每一幀,而關鍵是降低被調用一次。

最後的代碼應該是這樣的:

void Update() 
{ 
    if (Input.GetMouseButtonDown(0)) 
    { 
     RaycastHit hit; 

     if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit)) 
     { 
      bone = hit.collider.transform; 


      if (boneList.Contains(bone)) 
      { 
       //Object Clicked is already in List. Remove it from the List then UnHighlight it 
       boneList.Remove(bone); 
       UnHighlight(boneList); 
      } 
      else 
      { 
       //Object Clicked is not in List. Add it to the List then Highlight it 
       boneList.Add(bone); 
       Highlight(boneList); 
      } 
     } 
    } 
} 

你必須寫UnHighlight功能基本上恢復了在遊戲對象傳遞/轉換到默認狀態。