团结

2016-07-23 61 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

太感谢你了!肯定会试试这个 –