1:利用资源加载方式
1 using UnityEngine; 2 using System.Collections; 3 using UnityEngine.UI; 4 5 public class ChangeImage : MonoBehaviour 6 { 7 public Image myImage; 8 9 // Use this for initialization 10 void Start() 11 { 12 //需要自己在Assets下创建Resources文件夹,imagename是Resources下的图片名字 13 myImage.sprite = Resources.Load("imagename", typeof(Sprite)) as Sprite; // Image/pic 在 Assets/Resources/目录下 14 } 15 }
2:直接拉取赋值
1 using UnityEngine; 2 using System.Collections; 3 using UnityEngine.UI; 4 5 public class ChangeImage : MonoBehaviour 6 { 7 public Image myImage; 8 public Sprite mySprite; 9 // Use this for initialization 10 void Start() 11 { 12 myImage.sprite = mySprite; 13 } 14 }
3:网络下载更换
1 using UnityEngine; 2 using System.Collections; 3 using UnityEngine.UI; 4 5 public class ChangeImage : MonoBehaviour 6 { 7 public Image myImage; 8 9 // Use this for initialization 10 void Start() 11 { 12 StartCoroutine(WWWGetImage()); 13 } 14 15 16 IEnumerator WWWGetImage() 17 { 18 string url = "http://pic02.1sucai.com/190302/330853-1Z302203J169-lp.jpg"; 19 WWW www = new WWW(url); 20 yield return www; 21 if (string.IsNullOrEmpty(www.error)) 22 { 23 Texture2D tex = www.texture; 24 Sprite temp = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), Vector2.zero); 25 myImage.sprite = temp; 26 } 27 } 28 29 }