Search Unity

Changing a sprite in image canvas VIA C# script

Discussion in 'UGUI & TextMesh Pro' started by JoeD86, May 22, 2015.

  1. JoeD86

    JoeD86

    Joined:
    Apr 22, 2014
    Posts:
    2
    A quick question, if I want to change the source image of an "Image" component through a script, how would I go about that? I am trying to access the source image property but I can't figure out how.
     
  2. Zenov

    Zenov

    Joined:
    Jul 28, 2014
    Posts:
    53
    I think the easiest method would be to declare public variables and input your image and sprite directly into the inspector:
    Code (csharp):
    1.  
    2. public Image imageToChange;
    3. public Sprite newImage;
    4.  
    Then when you want to change it:
    Code (csharp):
    1. imageToChange.sprite = newImage;

    edit: don't forget to include the namespace of course :)
    Code (csharp):
    1. using UnityEngine.UI;
     
    shadowmere992 and JoeD86 like this.
  3. JoeD86

    JoeD86

    Joined:
    Apr 22, 2014
    Posts:
    2
    You sir or madam are my hero, thanks a ton!
     
    Zenov likes this.