简体   繁体   中英

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. 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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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