欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

unity 如何获取button文本的内容

时间:2021-09-20 09:09:15|栏目:.NET代码|点击:

如下就可以获取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后,结构如图:

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

发现其中竟然有一个叫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("找到这个按钮了!");

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

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

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

实验结果符合预期:

上一篇:C#页面之间跳转功能的小结

栏    目:.NET代码

下一篇:C#实现xml文件反序列化读入数据到object的方法

本文标题:unity 如何获取button文本的内容

本文地址:http://www.codeinn.net/misctech/176258.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有