Unity —— 移除/更换 UI Button 控件的文字的多此一举

编程入门 行业动态 更新时间:2024-10-25 08:17:53

Unity —— 移除/更换 UI Button <a href=https://www.elefans.com/category/jswz/34/1769529.html style=控件的文字的多此一举"/>

Unity —— 移除/更换 UI Button 控件的文字的多此一举

文章目录

  • 哪里多此一举
  • 为什么

我最近在写 Unity, 发现网上的移除/更换 UI Button 控件的文字,会有没用的代码

哪里多此一举

网上找到的代码:


using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;public class NewBehaviourScript : MonoBehaviour
{public Button btn;public Text txt;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>();text.text= "改变的文本值"; //此方法用于改变控件的文本值}
}
// --------------------- 
// 作者:金角大王:) 
// 来源:CSDN 
// 原文: 
// 版权声明:本文为博主原创文章,转载请附上博文链接!

但我觉得完全可以写成这样

using UnityEngine;
using UnityEngine.UI;public class RemoveButtonText : MonoBehaviour
{[Header("Sittings")][SerializeField] private string[] ButtonGameObjectNames;// Start is called before the first frame updatevoid Start(){// TODO 移除文本for(int i = 0; i < ButtonGameObjectNames.Length; i++)GameObject.Find(ButtonGameObjectNames[i]).GetComponent<Button>().GetComponentInChildren<Text>().text = null;}
}

为什么

请看下面这张图片

那个 StartGameButton 是个按钮
注意看 TextStartGameButton 的子 Object 对不对?
所以我们就可以用GetComponentInChildren<Text>()了而不用transform.Find("Text").GetComponent<Text>()
所以我说多此一举吗~

备注: 亲测有效

这是 “场景” 窗口里看到的,可以明显的看到有 Button 字样

这是 “游戏” 窗口里看到的
可以看到没有字了


提示:我只在 2020.1 的版本中做过测试,其他版本为做过测试,如结果不一致,欢迎评论区指正,不喜勿喷,谢谢

更多推荐

Unity —— 移除/更换 UI Button 控件的文字的多此一举

本文发布于:2024-02-14 05:01:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1761920.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控件   移除   文字   Unity   Button

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!