Unity UGUI替换Image图片的三种方式

来源:互联网 发布:粉尘防护口罩知乎 编辑:程序博客网 时间:2024/05/19 05:39
在NGUI中,我们可以直接用spriteName = “想要替换的图片名称”;  就可以很方便的替换资源
而UGUI却相对要麻烦一点,下面为大家介绍比较常用的三种替换方式。

一、

[csharp] view plain copy
  1. using UnityEngine;  
  2. using System.Collections;  
  3. using UnityEngine.UI;  
  4.     
  5. public class Test : MonoBehaviour  
  6. {  
  7.     
  8.     [SerializeField]  
  9.     Image myImage;  
  10.     
  11.     // Use this for initialization  
  12.     void Start()  
  13.     {  
  14.         myImage.sprite = Resources.Load("Image/pic"typeof(Sprite)) as Sprite;     // Image/pic 在 Assets/Resources/目录下  
  15.     }  
  16. }  

二、

[csharp] view plain copy
  1. using UnityEngine;  
  2. using System.Collections;  
  3. using UnityEngine.UI;  
  4.     
  5. public class Test : MonoBehaviour  
  6. {  
  7.     
  8.     [SerializeField]  
  9.     Image myImage;  
  10.     
  11.     [SerializeField]  
  12.     Sprite mySprite;  
  13.     
  14.     // Use this for initialization  
  15.     void Start()  
  16.     {  
  17.         myImage.sprite = mySprite;      // mySprite 为外部指定的图片资源  
  18.     }  
  19. }  

三、

[csharp] view plain copy
  1. using UnityEngine;  
  2. using System.Collections;  
  3. using UnityEngine.UI;  
  4.     
  5. public class Test : MonoBehaviour {  
  6.     
  7.     [SerializeField]  
  8.     Image myImage;  
  9.     
  10.     // Use this for initialization  
  11.     void Start () {  
  12.         StartCoroutine(GetImage());  
  13.     }  
  14.     
  15.     IEnumerator GetImage()  
  16.     {  
  17.         string url = "http://www.5dbb.com/images/logo.gif";  
  18.         WWW www = new WWW(url);  
  19.         yield return www;  
  20.         if (string.IsNullOrEmpty(www.error))  
  21.         {  
  22.             Texture2D tex = www.texture;  
  23.             Sprite temp = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0, 0));  
  24.             myImage.sprite = temp;  
  25.         }  
  26.     }  
  27. }