Changing a sprite in image canvas VIA C# script (139201)

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.

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

2 Answers

2

//attach a sprite from inspector or instantiate at runtime using Resources.Load
public Sprite newSprite;

this.transform.getComponent<UnityEngine.UI.Image>().sprite = newSprite;

Great answer.. how did you find this out?

Thank you! works like a charm!!

Thank You Sir

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Example: MonoBehaviour {

	public Image image;

	public  Sprite sprite;

	void Awake()
	{
		image.sprite = sprite;
	}

}