[英]How to change the text of a button on clicking it in UNITY?
我想在Unity中单击按钮时更改按钮的文本。 我是C#的新手。 请帮我!
我添加到我的Button元素的脚本
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Buttontextchange : MonoBehaviour {
Text Buy;
// Use this for initialization
void Start () {
Buy = transform.FindChild("Text").GetComponent<Text>();
}
// Update is called once per frame
void Update () {
}
public void clicked()
{
Debug.Log("Button Buy Clicked!");
Buy.text = "i am a button!";
}
}
您的问题来自文本和按钮的设置。
Buttontextchange组件位于Buttontext对象上。 我在图片上看到对象没有孩子。 但是您运行:
void Start () {
Buy = transform.FindChild("Text").GetComponent<Text>();
}
这可能是您得到错误的地方。 Text对象位于Button对象下,因此您可以在onClick调用中传递它。
public class Buttontextchange : MonoBehaviour
{
public void clicked(Text textRef)
{
Debug.Log("Button Buy Clicked!");
textRef.text = "i am a button!";
}
}
然后在检查器中,将文本对象拖到参数槽中。
编辑:用户想要更改单击按钮的颜色:
public class Buttontextchange : MonoBehaviour
{
public void clicked(Gameobject buttonObj)
{
Debug.Log("Button Buy Clicked!");
Text text = buttonObj.GetComponentInChildren<Text>(true);
if(text != null){
textRef.text = "i am a button!";´
}
Image image = buttonObj.GetComponent<Image>();
if(image != null){
image.color = newColor;
}
}
}
您缺少Text属性上的公共 c#关键字。 我对脚本进行了一些更改,因此您可以从Unity编辑器中分配文本和按钮引用
public class Buttontextchange : MonoBehaviour
{
public Button BuyButton;
public Text BuyText;
void Start()
{
BuyButton.onClick.AddListener(OnButtonClicked);
if (BuyText == null)
BuyText = BuyButton.GetComponentInChildren<Text>();
}
public void OnButtonClicked()
{
Debug.Log("Button Buy Clicked!");
BuyText.text = "i am a button!";
}
}
只需在单击事件Button.GetComponentInChildren(Text).text = "Button Clicked";
之后执行此操作Button.GetComponentInChildren(Text).text = "Button Clicked";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.