统一在不同的按钮点击上显示不同的文本

displaying different texts on different button clicks in unity

我正在使用 unity 制作一个用户交互式选择系统,其中有表示各种产品的按钮,当用户单击产品时,产品名称将按系统顺序依次显示。我使用 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;
            }


        }


    }



}

not使用OnGUI()函数。它旨在作为程序员的工具,而不是作为游戏中的 运行 的 UI。 .这是 Unity 中的一个简单的按钮和按钮点击检测器。

假设您需要两个按钮,下面的示例将展示如何做到这一点:

首先,创建两个按钮:

GameObject->UI->Button.

其次,将 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 是每个 Button 的子项。我不认为我可以让这更容易理解。 Here 是 Unity UI 的教程。