在Unity中,如何使用脚本访问预制件的子组件?

3

预制体层级:

按钮

1 文本

2 图片

我希望访问预制体中的图片子组件。

我尝试了以下代码:

GameObject addTypeButton = (GameObject)Instantiate(prefabButton);
addTypeButton.transform.SetParent(ParentPanel, false);
//set text
addTypeButton.GetComponentInChildren<Text>().text ="Some string";
//get image
WWW www = new WWW("someImagelink");
yield return www;
//set image
addTypeButton.GetComponentInChildren<Image>().sprite = Sprite.Create(www.texture, new Rect(0, 0, www.texture.width,www.texture.height), new Vector2(0, 0));

然而,上述代码正在访问内置的按钮(Image script)的图像脚本。而不是UI Image组件。

我该如何访问UI Image(子)组件呢?

请帮忙解决。

谢谢!

3个回答

16

原因

GetComponentInChildren 还将返回gameObject本身上的组件。

public Component GetComponentInChildren(Type t);

Returns the component of Type type in the GameObject or any of its children using depth first search.

解决方案

  1. If the index of child GameObject 1 Text and 2 Image is fixed. You can get them by Transform.GetChild(index).

    var buttonTransform = addTypeButton.transform;
    var text = buttonTransform.GetChild(0);
    var image = buttonTransform.GetChild(1);
    
  2. If the order is not fixed, use Transform.Find(childName).

    var buttonTransform = addTypeButton.transform;
    var text = buttonTransform.Find("1 Text");
    var image = buttonTransform.Find("2 Image");
    
  3. The safest solution:

    Drag your prefab to scene and attach a script to your Button GameObject:

    using UnityEngine;
    using UnityEngine.UI;
    public class MyButton : MonoBehaviour
    {
        public Text text;
        public Image image;
    }
    

    Then drag 1 Text and 2 Image to text and image field in the inspector of the Button. how
    Remember to press apply button and Ctrl+S to save that into your prefab.

    In this way you can access the text and image like:

    var mybutton = addTypeButton.GetComponent<MyButton>();
    mybutton.text.text = "Some string";
    mybutton.image.sprite = Sprite.Create(...);
    

有3个答案,但只有这一个能够完成任务。GetChildFind更好。 - undefined
我要补充的是,仅依赖对象名称或层次顺序可能并不总是最安全的解决方案。为了更可靠的解决方案,你可以使用GetComponentsInChildren<Image>()并检查返回的_Image_是否与按钮上的那个不同(但这样会更慢)。 - undefined

0
访问子对象之前,请确保在实例化后启用或禁用之前,预制体中的该子对象已启用。就像在我的情况下,我有一个带有图像子对象的UI Text游戏对象。我在预制体中将其禁用,希望在脚本中通过引用启用它。只有在预制体中保持图像(子对象)组件启用时,它才起作用。

-1
尝试更改
addTypeButton.GetComponentInChildren().sprite = Sprite.Create(www.texture, new Rect(0, 0, www.texture.width,www.texture.height), new Vector2(0, 0));

addTypeButton.GetComponent().sprite = Sprite.Create(www.texture, new Rect(0, 0, www.texture.width,www.texture.height), new Vector2(0, 0));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接