首页 文章

在Unity中实例化UI对象并且不在屏幕中显示?

提问于
浏览
0

我在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);
}

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

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

有人能给我任何关于这种行为的线索吗?

1 回答

  • 0

    好吧,看起来你分配精灵的方式是不正确的 . 精灵通过 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);
    }
    

相关问题