how to change image with script unity code example

Example 1: how to change a image with code unity

// Change From GameOject
public GameObject GameObjectWithImage;
public Sprite ImageYouWant;
GameObjectWithImage.GetComponent<Image>().sprite = ImageYouWant

// Change From Image
public Image Image;
public Sprite ImageYouWant;
Image.sprite = ImageYouWant

Example 2: set sprite unity

public Sprite sprite1; // Drag your first sprite here
public Sprite sprite2; // Drag your second sprite here

private SpriteRenderer spriteRenderer; 

void Start ()
{
    spriteRenderer = GetComponent<SpriteRenderer>(); // we are accessing the SpriteRenderer that is attached to the Gameobject
    if (spriteRenderer.sprite == null) // if the sprite on spriteRenderer is null then
        spriteRenderer.sprite = sprite1; // set the sprite to sprite1
}

void Update ()
{
    if (Input.GetKeyDown (KeyCode.Space)) // If the space bar is pushed down
    {
        ChangeTheDamnSprite (); // call method to change sprite
    }
}

void ChangeTheDamnSprite ()
{
    if (spriteRenderer.sprite == sprite1) // if the spriteRenderer sprite = sprite1 then change to sprite2
    {
        spriteRenderer.sprite = sprite2;
    }
    else
    {
        spriteRenderer.sprite = sprite1; // otherwise change it back to sprite1
    }
}