Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Changing the background image of a menu canvas in unity

Discussion in 'Scripting' started by DoomDude99, May 11, 2019.

  1. DoomDude99

    DoomDude99

    Joined:
    May 11, 2019
    Posts:
    87
    How can I change the background image of a canvas which looks like

    unity_change_background.png



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

    There are similar questions:

    https://forum.unity.com/threads/how-to-change-sprite-image-from-script.212307/
    https://forum.unity.com/threads/changing-sprite-during-run-time.211817/
    https://forum.unity.com/threads/mini-tutorial-on-changing-sprite-on-runtime.212619/

    but focus only on sprites.

    This question:

    https://gamedev.stackexchange.com/q...e-background-image-when-press-button-in-unity

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

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
  3. DoomDude99

    DoomDude99

    Joined:
    May 11, 2019
    Posts:
    87
    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?
     
  4. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    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.
     
  5. DoomDude99

    DoomDude99

    Joined:
    May 11, 2019
    Posts:
    87
    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

    Code (CSharp):
    1.     Image m_Image;
    2.     //Set this in the Inspector
    3.     public Sprite m_Sprite;
    4.  
    5.     void Start()
    6.     {
    7.         //Fetch the Image from the GameObject
    8.         m_Image = GetComponent<Image>();
    9.     }
    from the docs I'm not sure how m_Sprite is assigned a value.
     
  6. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    You want Texture2D.LoadImage and then Sprite.Create. Then assign the result to .sprite property as GroZZleR suggests.
     
    DoomDude99 likes this.
  7. DoomDude99

    DoomDude99

    Joined:
    May 11, 2019
    Posts:
    87
    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?