2017-04-11 188 views
-1

在編輯器中我在菜單中做了:GameObject> UI> Button 現在我在層次結構中使用一個按鈕的畫布。 現在我想要當我運行遊戲時,它不會顯示按鈕,只有當我按下退出鍵時,它會顯示按鈕。如何隱藏遊戲視圖中的UI按鈕並在按下退出鍵時顯示按鈕?

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 
using UnityEngine.UI; 

public class NodesGenerator : MonoBehaviour { 

    public Button btnGenerate; 

    private void Start() 
    { 
     Button btn = btnGenerate.GetComponent<Button>(); 
     btn.onClick.AddListener(TaskOnClick); 
    } 

    void TaskOnClick() 
    { 
     Debug.Log("You have clicked the button!"); 
    } 

我想,當我按下退出鍵btn將顯示並再次逃脫不會顯示。運行遊戲時的默認狀態不顯示按鈕。

回答

3

想象一下,通過「隱藏」,您意味着您停用了持有按鈕的對象,如果您按下了Escape鍵,則需要檢查Update功能。如果你確實擊中了它,你只需要扭轉按鈕的活動狀態,就完成了。

作爲一個方面說明,在您的Start函數中,您不需要再次獲取Button組件,因爲您已經在btnGenerate變量中引用了它。所以你可以直接將監聽器添加到你的btnGenerate變量中。

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 
using UnityEngine.UI; 

public class NodesGenerator : MonoBehaviour { 

    public Button btnGenerate; 

    private void Start() 
    { 
     btnGenerate.onClick.AddListener(TaskOnClick); 
    } 

    void Update() 
    { 
     if (Input.GetKeyDown(KeyCode.Escape)) 
     { 
      btnGenerate.gameObject.SetActive(!btnGenerate.gameObject.activeSelf); 
     } 
    } 

    void TaskOnClick() 
    { 
     Debug.Log("You have clicked the button!"); 
    } 
}