unity button文本内容获取 unity 怎样获取button文本的内容

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

unity button文本内容获取 unity 怎样获取button文本的内容

yguoelect   2021-04-13 我要评论
想了解unity 怎样获取button文本的内容的相关内容吗,yguoelect在本文为您仔细讲解unity button文本内容获取的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:unity获取button,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后,结构如图:

先仔细观察一下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在子目录上.

实验结果符合预期:

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们