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

如何在代码中替换面板上的背景图像?C#,c#,image,unity3d,background,panel,C#,Image,Unity3d,Background,Panel,在我在Unity3d中构建的应用程序中,我希望能够让用户为主面板选择背景图像。目前,当我调试变量时,我得到了null。如果有人能给我指出正确的方向 public Image Background; public Sprite theImage; // Use this for initialization void Start () { theImage = Resources.Load<Sprite>("Sprites/sf1"); Debug.Log(the

在我在Unity3d中构建的应用程序中,我希望能够让用户为主面板选择背景图像。目前,当我调试变量时,我得到了null。如果有人能给我指出正确的方向

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);
公共图像背景;
公共精灵形象;
//用于初始化
无效开始()
{
theImage=Resources.Load(“精灵/sf1”);
Debug.Log(图像);
Background.GetComponent().sprite=theImage;
Debug.Log(图像);

谢谢!

需要记住的一点是,没有面板。“但我刚刚创建了一个”我听你说。当然,Unity会让你认为你做到了。但是如果你看看它创建的游戏对象,你会发现它只不过是一个带有RectTransform组件和Image组件的游戏对象

因此,如果您要将自己的组件添加到此面板中,您所需要做的就是按照

Image image = GetComponent<Image>();
image.sprite = mySprite;
Image=GetComponent();
image.sprite=mySprite;
如果不是针对未分配的
背景
图像,那么您的代码几乎就在那里了