首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何更有效地更改每个父子组件文本?Unity C#

如何更有效地更改每个父子组件文本?Unity C#
EN

Stack Overflow用户
提问于 2016-07-13 13:06:36
回答 1查看 208关注 0票数 0

我找到了更有效的代码,可以从父游戏对象中找到每个子组件,并更改游戏对象的每个子组件文本。

gameobject的每个子组件文本都有不同的值,每个依赖于变量。

这是屏幕截图

这是我的代码:

代码语言:javascript
复制
public Dictionary <string, GameObject> product = new Dictionary<string, GameObject>();
    public Dictionary <string, Text> property = new Dictionary<string, Text> ();

dex = productMargaret.FindIndex(j => j.productID == 15);
            product["Mayonnaise"] = GameObject.Find("btnMayonnaise");

            property["qty"] = gameObject.transform.GetChild (1).GetComponent<Text> (); //+ productMargaret[dex].qty.ToString;
            property["qty"].text = productMargaret[dex].qty.ToString;
            property["price"] = gameObject.transform.GetChild (2).GetComponent<Text> (); //+ productMargaret[dex].price.ToString;
            property["price"].text = "@ " + productMargaret[dex].price.ToString;
            property["have"] =  gameObject.transform.GetChild (2).GetComponent<Text> (); //+ productMargaret[dex].have.ToString;
            property["have"].text = "You Have : " + productMargaret[dex].have.ToString;

这就是代码不工作的原因。

该怎么做呢?为了更有效的方式,比如使用循环。

谢谢

EN

回答 1

Stack Overflow用户

发布于 2016-07-13 13:34:04

假设您的按钮的名称类似于btnProductID_15、btnProductID_16、btnProductID_17,并附加了按钮组件。您可以简单地在父gameObject上执行以下操作:

代码语言:javascript
复制
public Dictionary <string, string> property = new Dictionary<string, Text> (); //the Key would be btnProductID_15...btnProductID_N and value will be the label of the button.
List<Button> btnList = GetComponentsInChildren<Button>();
foreach (Button item in btnList)
{
   Text textField = GetComponentInChildren<Text>();
   textField.text = property[item.name];
}

当然,您需要填充"property“字典accordingly....And now am。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38343043

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档