简体   繁体   English

如何用代码替换面板上的背景图像? C#

[英]How do I replace a background image on a panel in code? C#

In the app I'm building in Unity3d, I want to be able to have the user choose a background image for the main panel. 在我正在Unity3d中构建的应用程序中,我希望能够让用户为主面板选择背景图像。 At the moment, I'm getting null when I debug out the variables. 目前,当我调试变量时,我得到的是空值。 If someone could point me in the right direction. 如果有人可以指出我正确的方向。

public Image Background;
public Sprite theImage;


// Use this for initialization
void Start () 
{
    theImage = Resources.Load<Sprite>("Sprites/sf1");
    Debug.Log(theImage);
    Background.GetComponent<Image>().sprite=theImage;
    Debug.Log(theImage);

Thanks! 谢谢!

One thing to remember is that there is no such thing as a panel. 要记住的一件事是,没有面板这样的东西。 "But I just created one" I hear you say. “但是我只是创造了一个。”我听你说。 Sure, Unity makes you think you did. 当然,Unity让您以为自己做到了。 But if you look at the gameobject it created, you'll see it's nothing more than a GameObject with a RectTransform component and and Image component. 但是,如果您查看它创建的游戏对象,就会发现它不过是带有RectTransform组件和Image组件的GameObject。

So if you were to add your own component to this Panel, all you'd need to do is something along the lines of 因此,如果要在此面板中添加自己的组件,则要做的只是遵循以下步骤:

Image image = GetComponent<Image>();
image.sprite = mySprite;

So your code is almost there, if not for the unassigned Background image. 因此,如果没有未分配的Background图片,您的代码几乎就在那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM