协程
控制物体移动到指定位置
cube绕Plane边框移动了一圈
public class CubeScript : MonoBehaviour {
#region 协程介绍
/* 协程:一个返回值是 IEnumerator 的接口
* 协程功能:可以实现将一个方法拆分成多步执行
* yield: 在这里的意思是等一个条件满足后再从这里继续
* yield return 0 ; 高速协程等待下一帧,直到继续执行为止
* yield return new WaitForSeconds(4f); 等待5s后,再从这里继续
* 协程的开启和停止:
* 开启协程(两种形式):
* StartCoroutine(RoutineForward());
* StartCoroutine("RoutineForward");
* 停止协程:
* StopCoroutine(RoutineForward());
* 协程和线程不是一回事: 线程是操作系统级别,协程是编辑器级别。 */
#endregion
private Vector3 Dir = new Vector3();
private float speed = 0.05f;
void Start () {
StartCoroutine(RoutineForward());
}
void FixedUpdate()
{
transform.position += Dir;
}
//自己写一个有返回值的方法,编译器的协程回去调用它【IEnumerator:接口】
IEnumerator RoutineForward()
{
print("编译器协程调用正向走的方法");
//一开始cube是往前直走的
//往前走
Dir.z = speed;
Dir.x = 0;
//4秒后要屏蔽掉正前方,往左拐走
yield return new WaitForSeconds(4f);
//往左走
Dir.z = 0;
Dir.x = -speed;
yield return new WaitForSeconds(4f);
Dir.z = -speed;
Dir.x = 0;
yield return new WaitForSeconds(4f);
Dir.z = 0;
Dir.x = speed;
yield return new WaitForSeconds(4f);
//停止
Dir.z = 0;
Dir.x = 0;
}
void OnDisable()
{
StopCoroutine(RoutineForward());
}
}
WWW
下载图片(加载图片)
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
using System.IO;
public class myWWWDownPic : MonoBehaviour {
[SerializeField]
private Image m_Image;
const string m_ImageURL = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png";
string m_ImageLocalURL = "";
private void Start()
{
m_ImageLocalURL = Application.dataPath + "/Resources/HaHa.png";
StartCoroutine(LoadImageFromLocal());
}
private IEnumerator LoadImageFromLocal()
{
while (true)
{
if (File.Exists(m_ImageLocalURL))
{
//特别注意如果使用Resources.Load不需要声明文件的格式
Texture2D image2D = Resources.Load<Texture>("HaHa") as Texture2D;
print(image2D.name);
m_Image.sprite = Sprite.Create(
image2D,new Rect(0,0,image2D.width,image2D.height),
new Vector2(0.5f,0.5f));
使用www类也可以加载本地资源【c盘 d盘 任意本地路径】
//string s = @"C:\Users\lanou3g\Desktop\UnityWork\WWWAndYieldClass\Assets\Resources";
//WWW www = new WWW("file://" + s + @"\HaHa.jpg");
//Sprite spr = Sprite.Create(
// image2D, new Rect(0, 0, image2D.width, image2D.height),
// new Vector2(0.5f, 0.5f));
//m_Image.sprite = spr;
}
else
{
StartCoroutine(DownLoadImageFromNet(m_ImageURL));
}
yield return null;
if (m_Image.sprite !=null)
{
break;
}
}
}
private IEnumerator DownLoadImageFromNet(string m_ImageURL)
{
WWW imageWWW = new WWW(m_ImageURL);
while (!imageWWW.isDone)
{
print(imageWWW.progress);
yield return null;
}
if (imageWWW.isDone)
{
//第一次下载完毕后写入本地,将图片资源本地持久化
File.WriteAllBytes(m_ImageLocalURL,imageWWW.texture.EncodeToPNG());
//刷新编辑器资源
UnityEditor.AssetDatabase.Refresh();
}
}
}