團結

2016-07-23 57 views
1

顯示不同的按鈕點擊不同的文本,我使用統一地方,有按鈕,表示各種產品和產品名稱是低於其他被顯示在系統的順序一個使用戶交互式選擇系統時,用戶點擊在產品上。我已經使用OnGUI()函數顯示產品名稱。但是在我的輸出中,所有的名字都被印刷得超級強烈。團結

我綁使用靜態變量i(最初定義爲0)遞增GUI.label的y位置。我嘗試在每次點擊時增加i的值,並將其添加到GUI.label的y位置。現在當我點擊第二個按鈕時,第一個按鈕標籤和第二個按鈕標籤都會移動到新的座標系。

using UnityEngine; 
using UnityEngine.EventSystems;// 1 
using UnityEngine.UI; 

``public class Example : MonoBehaviour, IPointerClickHandler // 2 

// ... And many more available! 
{ 
    SpriteRenderer sprite; 
    Color target = Color.red; 
    int a=200,b=100; 

    public GUIText textObject; 
    public bool showGUI; 
    public int s=0; 



    public static int i=0; 



    void Awake() 
    { 
     sprite = GetComponent<SpriteRenderer>(); 
    } 

    void test() 
    { 
     i = i + 20; 

     OnGUI(); 
    } 

    void Update() 
    { 
     if (sprite) 
      sprite.color = Vector4.MoveTowards(sprite.color, target, Time.deltaTime * 10); 
    } 

    public void OnPointerClick(PointerEventData eventData) // 3 
    { 
     showGUI = true; 
     Debug.Log(gameObject.name); 
     target = Color.blue; 
     PlayerPrefs.SetString ("Display", gameObject.name); 
     s = 1; 
     test(); 


    } 

    void OnGUI() 
    { 

     if (s == 1) { 

      GUI.color = Color.red; 
      GUIStyle myStyle = new GUIStyle (GUI.skin.GetStyle ("label")); 
      myStyle.fontSize = 20; 

      GUI.Label (new Rect (a, b, 100f, 10f), ""); 

      if (showGUI) { 

       //GUI.Box (new Rect (a,b+i, 300f, 100f), ""); 
       GUI.Label (new Rect (a, b + i, 300f, 100f), gameObject.name, myStyle); 

       s = 0; 
      } 


     } 


    } 



} 

回答

2

不要not使用OnGUI()功能。它的目的是爲程序員提供一種工具,而不是將在遊戲中運行的用戶界面。 。這裏是Unity中一個簡單的按鈕和按鈕點擊檢測器。

比方說,你需要兩個按鈕,下面的例子將展示如何做到這一點:

首先,創建兩個按鈕:

遊戲對象 - >UI - >按鈕

其次,包括UnityEngine.UI;命名空間using UnityEngine.UI;

聲明Buttons變量:

public Button button1; 
public Button button2; 

創建一個回調函數的每個Button被點擊時會被調用:

private void buttonCallBack(Button buttonPressed) 
{ 
    if (buttonPressed == button1) 
    { 
     //Your code for button 1 
    } 

    if (buttonPressed == button2) 
    { 
     //Your code for button 2 
    } 
} 

Buttons連接到回調函數(註冊按鈕事件)當啓用腳本時。

void OnEnable() 
{ 
    //Register Button Events 
    button1.onClick.AddListener(() => buttonCallBack(button1)); 
    button2.onClick.AddListener(() => buttonCallBack(button2)); 
} 

斷開Buttons從該回調函數(未經註冊按鈕事件)時,腳本被禁用。

void OnDisable() 
{ 
    //Un-Register Button Events 
    button1.onClick.RemoveAllListeners(); 
    button2.onClick.RemoveAllListeners(); 
} 

修改連接到按鈕上的文字:

button1.GetComponentInChildren<Text>().text = "Hello1"; 
button2.GetComponentInChildren<Text>().text = "Hello2"; 

您使用GetComponentInChildren因爲創造了Text被製成每個按鈕的孩子。我不認爲我可以讓這更容易理解。 Here是Unity UI的教程。

+0

太感謝你了!肯定會試試這個 –