软件编程
位置:首页>> 软件编程>> C#编程>> unity 如何获取button文本的内容

unity 如何获取button文本的内容

作者:yguoelect  发布时间:2022-01-29 19:31:04 

标签:unity,button文本,内容

如下就可以获取button中的文本内容


using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class ButtonContent : MonoBehaviour{
    public Button btn;
    void Start(){
        btn = GameObject.Find("填写button名").getComponent<Button>(); //-----------(1)
        Text text = btn.transform.Find("Text").getComponent<Text>(); //------------(2)
        //或者吧(1)(2)合并成:
        //  Text text = GameObject.Find("填写button名/Text").getComponent<Text>();
        Debug.Log(text.text.toString());
        //其实就一条语句
 //     Debug.Log(GameObject.Find("填写button名/Text").getComponent<Text>().text.toString());
    }
}

补充:Unity获取任意GameObject下节点Text、Button等组件

核心只有一句:


Text/Button compo=GameObject.Find("任意button/text节点名称").GetComponent();

或者:


Text text = gameobject.transform.Find("Text名称").GetComponent();

补充:Unity3D如何修改Button显示的文字以及深入了解Button组件

在创建了一个Button后,结构如图:

unity 如何获取button文本的内容

先仔细观察一下Button的Inspector视图:

unity 如何获取button文本的内容

发现其中竟然有一个叫Button的脚本组件.

新建脚本,代码如下,并将该脚本绑定给Canvas组件:


using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine;
public class btn1 : MonoBehaviour
{
   // Start is called before the first frame update
  public Button btn;
   void Start()
   {
   }
   // Update is called once per frame
   void Update()
   {
       GameObject go = GameObject.Find("Butt");
       Text text=go.GetComponentInChildren<Text>();
       text.text="天桑在玩CSGO";
       Debug.Log(text.text);
   }
}

1.首先通过GameObject.Find()找到名字为Butt的游戏物体.

2.通过GetComponentInChildren()获得子目录下类型为T的组件.

(这里我之前用GetComponent试过不行,是因为Button的Text在子目录下)

3.我们还可以获得Button组件:


GameObject go = GameObject.Find("Butt");
       Button button=go.GetComponent<Button>();
       if(button)Debug.Log("找到这个按钮了!");

这两段代码合并后的输出结果为:

unity 如何获取button文本的内容

这表明这两个组件都找到了.

这样一看,Button的结构就很清楚了,Button在第一级目录上,附带生成的Text在子目录上.

实验结果符合预期:

unity 如何获取button文本的内容

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。

来源:https://blog.csdn.net/yguoelect/article/details/70666396

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com