在 Unity 中实例化 UI 对象但没有显示在屏幕上?

Instantiate UI object in Unity and doesn't show in the screen?

我在 Unity (CSharp) 中有这样的代码:

public GameObject button;
public GameObject panel;

void Start () {
    button.transform.SetParent (panel.transform);
    Sprite shape = Resources.Load<Sprite>("Logo");
    var img = button.transform.GetComponent("Image") as Image;
    img.sprite = shape;
    img.color = new Color (50, 50, 50, 50);
}

现在,这是我的场景在播放之前的样子:

The button in the left side is the one i will try to instantiate in my code and "Albumes" is the Panel.

然后,当我按下播放按钮时,我得到这个:

I can see in the inspector that the sprite was successfuly loaded

有人可以给我任何关于此行为的线索吗?

嗯,看来您分配精灵的方式不正确。 Sprite 通过 Sprite.Create 赋值。你可以试试这个,

public GameObject button;
public GameObject panel;

void Start () {
    button.transform.SetParent (panel.transform);
    Sprite shape = Resources.Load<Sprite>("Logo");
    var img = button.gameObject.GetComponent<Image>();
    img.sprite = Sprite.Create(shape.texture,img.sprite.rect,new Vector2(0.5f,0.5f));
    img.color = new Color (50, 50, 50, 50);
}