Changing the background image of a menu canvas in unity

How can I change the background image of a canvas which looks like


in C# (the script being a handler to a button on the canvas)?

There are similar questions:

but focus only on sprites.

This question:

suggests using SpriteRenderers but it’s not clear to me (being a beginner) how the image (a property of the canvas) is fetched and changed by the renderer and whether or not it’s scaled to fit the screen.

https://docs.unity3d.com/ScriptReference/UI.Image-sprite.html

The sample code is attached to the image game object, but, in my case, it should be run when the user clicks a button that uses the image as a background. How can I lookup the sprite, scale it and replace the original background image?

I’m not entirely sure what you’re asking. To change the visual portion of an Image component, you assign a sprite to its aptly named sprite property. The sprite will be scaled to whatever the Image anchors / other settings tell it to.

The workflow is the following:

– grab an image from a web service
– save it locally
– load and change the current background of the canvas

In

    Image m_Image;
    //Set this in the Inspector
    public Sprite m_Sprite;

    void Start()
    {
        //Fetch the Image from the GameObject
        m_Image = GetComponent<Image>();
    }

from the docs I’m not sure how m_Sprite is assigned a value.

You want Texture2D.LoadImage and then Sprite.Create. Then assign the result to .sprite property as GroZZleR suggests.

1 Like

This may sound stupid, but how do you assign the sprite created from the image that was read to the background image of the canvas?