【问题标题】:Unity change image of child component of buttonunity改变按钮子组件图片
【发布时间】:2018-12-02 17:38:20
【问题描述】:
void Start () {
    foreach (Sprite texture in spriteImages) {
        GameObject button = Instantiate (shopButtonPrefab) as GameObject;
        button.GetComponentInChildren<Image>().sprite = texture;
        button.transform.SetParent (shopButtonContrainer.transform, false);

    }
}

我有一个按钮预制件,即一个按钮,带有一个图像组件作为子组件。我不确定为什么我的代码会更改与孩子相反的按钮精灵图像。我改变孩子很重要,我改变它的图像也是一个圆圈,所以我不想丢失按钮已经是矩形默认图像。如何更改子图像,同时将按钮图像保留为默认值?

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    GetComponentInChildren&lt;t&gt;() 使用深度优先搜索在游戏对象或其子对象中获取请求的组件,这意味着它将首先检查父对象,然后返回它找到的第一个实例。您可以使用 GetComponentsInChildren&lt;t&gt;() 这将返回一个数组,其中包含在父级及其子级中找到的所有组件。

    另一种方法是获取第一个子元素,并在该子元素上调用 GetComponent&lt;t&gt;()

    要跳过父级,使用GetComponentsInChildren&lt;t&gt;() 循环遍历所有找到的组件,如果它们不是父级上的t,则更改其纹理。

    这是一个例子,它并不是最有效的方法:

    void Start () {
    
        foreach (Sprite texture in spriteImages) {
            GameObject button = Instantiate (shopButtonPrefab) as GameObject;
            Image buttonImage= button.GetComponent<Image>();
            Image[] images = button.GetComponentsInChildren<Image>().sprite = texture;
            foreach(Image image in images) {
                if(image != buttonImage) 
                {
                    image.sprite = texture;
                    break;
                }
            }
            button.transform.SetParent (shopButtonContrainer.transform, false);
        }
    }
    

    【讨论】:

    • 那么我怎样才能让它跳过父母呢?
    • 您不能让该功能跳过父级,但是我回答的最后一行为您提供了另一种获取子级图像的方法。
    • 完全错过了。因为我对这一切都很陌生,所以我的 for 循环中的 if 语句会检查它是否在父级上?谢谢!
    • 大功告成!非常感谢。出于兴趣,需要休息吗?
    猜你喜欢
    • 2018-03-11
    • 2013-12-08
    • 2012-01-04
    • 1970-01-01
    • 2016-12-09
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    相关资源
    最近更新 更多