/**
*Copyright(C) 2017 by MMHD
*All rights reserved.
*FileName: LoadPic.cs
*Author: Joel
*Date: 2018/1/18
*Description:
*History: By_307035570
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class LoadPic : MonoBehaviour {
public string url = "http://www.manew.com/template/manew2016/images/logo.png";
void Awake()
{
//www加载网络图片更新至按钮
//StartCoroutine(Load(url));
// UnityWebRequestThe 加载
//StartCoroutine(GetText());
}
IEnumerator Start()
{
using (WWW www = new WWW(url))
{
yield return www;
//Renderer renderer =transform.GetComponent<Renderer>();
//renderer.material.mainTexture = www.texture;
Texture2D tex = new Texture2D(152, 50);
www.LoadImageIntoTexture(tex);
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, 152, 50), Vector2.zero);
transform.GetComponent<Image>().sprite = sprite;
}
}
/// <summary>
/// UnityWebRequestThe 网络请求获取
/// </summary>
/// <returns></returns>
IEnumerator GetText()
{
using (UnityWebRequest www = UnityWebRequest.Get(url))
{
yield return www.Send();
if (www.isError)
{
Debug.Log(www.error);
}
else
{
int width = 1920;
int height = 1080;
byte[] results = www.downloadHandler.data;
Texture2D texture = new Texture2D(width, height);
texture.LoadImage(results);
yield return new WaitForSeconds(0.01f);
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
transform.GetComponent<Image>().sprite = sprite;
yield return new WaitForSeconds(0.01f);
Resources.UnloadUnusedAssets();
}
}
}
/// <summary>
/// www 网络加载图片更新至按钮
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
IEnumerator Load(string path)
{
WWW www = new WWW(path);
yield return www;
if (!string.IsNullOrEmpty(www.error))
{
Debug.Log(www.error);
}
else
{
if (www.isDone)
{
Texture2D tex = new Texture2D(152,50);
www.LoadImageIntoTexture(tex);
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, 152,50), Vector2.zero);
GameObject btngo = GameObject.Find("Button");
if (btngo)
{
btngo.GetComponent<UnityEngine.UI.Image>().sprite = sprite;
}
}
}
}
}
原文:https://blog.csdn.net/htwzl/article/details/79109073