控件的文字的多此一举"/>
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
是个按钮
注意看 Text
是 StartGameButton
的子 Object 对不对?
所以我们就可以用GetComponentInChildren<Text>()
了而不用transform.Find("Text").GetComponent<Text>()
所以我说多此一举吗~
备注: 亲测有效
这是 “场景” 窗口里看到的,可以明显的看到有 Button 字样
这是 “游戏” 窗口里看到的
可以看到没有字了
提示:我只在 2020.1 的版本中做过测试,其他版本为做过测试,如结果不一致,欢迎评论区指正,不喜勿喷,谢谢
更多推荐
Unity —— 移除/更换 UI Button 控件的文字的多此一举
发布评论