网络请求图片
usingUnityEngine;
usingSystem.Collections;
usingUnityEngine.UI;
usingSystem.Collections.Generic;
usingSystem;
public class WWWScript:MonoBehaviour{
public RawImage image;
UIManager uimanager;
string url="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1496380007&di=8aaa430ef4656836fc3113b357295a6e&imgtype=jpg&er=1&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimgad%2Fpic%2Fitem%2F0eb30f2442a7d933a01ea656a74bd11373f00164.jpg";
voidAwake(){
uimanager=GameObject.Find("UIManager").GetComponent();
}
voidStart(){
StartCoroutine("LoadTexture");
StartCoroutine(LoadTexture(url,delegate(Textureobj){
if(uimanager!=null){
uimanager.image.texture=obj;
}
}));
}
IEnumeratorLoadTexture(){
//创建WWW对象,传入一个URL,Url既可以是Web的路径,也可以是本地的路径file://
//网络请求有两种Get Post
WWWwww=newWWW(url);
//挂起当期程序片段,等待资源下载完成后继续执行
yield return www;
if(string.IsNullOrEmpty(www.error)){//判断错误是否为空,为空则下载完成
image.texture=www.texture;
}else{
Debug.Log(www.error);
}
public IEnumerator LoadTexture(stringurl,ActioncallBack){
WWWwww=newWWW(url);
//挂起当期程序片段,等待资源下载完成后继续执行
yield return www;
print("fin");
if(string.IsNullOrEmpty(www.error)){
callBack.Invoke(www.texture);
//callBack(www.texture);
}else{
Debug.Log(www.error);
//弹窗
}
}
}
网络请求视频并播放
usingUnityEngine;
usingSystem.Collections;
usingUnityEngine.UI;
usingSystem.IO;
publicclassPlayMovieScript:MonoBehaviour{
//Unity支持的播放视频格式.MOV.mpq.mpeq.mp4.avi.asf.oqq
//视频地址
stringurl="http://www.runoob.com/try/demo_source/movie.ogg";
//进度条
public Slider sli;
//显示视频的控件
public RawImageraw Image;
//文件名
stringfileName="movie.ogg";
//文件存储路径
stringpath;
//接受下载下来的视频资源
MovieTexturemovieTexture;
//播放音频
AudioSourceaudioSource;
voidStart(){
//允许在后台运行
Application.runInBackground=true;
path=Application.dataPath+"/Resources/"+fileName;
audioSource=gameObject.GetComponent();
}
publicvoidPlayMovie(){
if(File.Exists(path)){
Play();
}else{
StartCoroutine("DownLoad");
}
}
publicvoidPlay(){
print("sdfs");
movieTexture=Resources.Load("movie");
//audioSource.clip=Resources.Load("movie");
if(movieTexture==null||movieTexture.isReadyToPlay==false){
Debug.Log("无法播放");
return;
}
rawImage.texture=movieTexture;
audioSource.clip=movieTexture.audioClip;
movieTexture.Play();//播放视频
audioSource.Play();//播放音频
}
IEnumeratorDownLoad(){
WWWwww=newWWW(url);
//等待下载完成,并等待更新进度条
while(!www.isDone){
sli.value=www.progress;
yieldreturn0;
}
sli.value=1.0f;
//保存文件
if(string.IsNullOrEmpty(www.error)){
File.WriteAllBytes(path,www.bytes);
while(!File.Exists(path)){//存在就代表下载完成
yieldreturn0;
}
www.Dispose();//释放缓存资源
UnityEditor.AssetDatabase.Refresh();//刷新
Play();
}else{
Debug.Log(www.error);
}
}
}