在博客發現一篇關于協程的文章,文章內容循序漸進,條理清晰,對于入門來說很有幫助,在此做個記錄,以供日后查閱,原文鏈接
代碼實作
using UnityEngine;
using System.Collections;
public class MoveExample : MonoBehaviour
{
public Vector3[] path;
public Color[] colors;
public float moveSpeed;
void Start()
{
StartCoroutine(MoveOnPath(true));
}
IEnumerator MoveOnPath(bool loop)
{
do
{
for (int i = 0; i < 4; i++)
{
yield return StartCoroutine(ChangeColor(colors[i]));
yield return StartCoroutine(MoveToPosition(path[i],moveSpeed));
}
}
while(loop);
}
IEnumerator MoveToPosition(Vector3 target,float speed)
{
float sp = speed;
while(transform.position != target)
{
transform.position = Vector3.MoveTowards(transform.position, target, sp * Time.deltaTime);
sp+=0.01f;
moveSpeed = sp;
yield return 0;
}
}
IEnumerator ChangeColor(Color color)
{
this.gameObject.GetComponent<MeshRenderer>().materials[0].color = color;
yield return 0;
}
}
引數設定
路徑所途徑的四個點的坐標:
| 點 | 坐標 |
|---|---|
| 1 | (-1,-1,3) |
| 2 | ( 1,-1,3) |
| 3 | ( 1, 1,3) |
| 4 | (-1, 1,3) |
每切換一個坐標點,便更改一次顏色:
| 點 | 顏色 |
|---|---|
| 1 | 紅 |
| 2 | 藍 |
| 3 | 黃 |
| 4 | 綠 |
Unity中引數截圖
路途坐標:

切換顏色: 
效果演示

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/291574.html
標籤:其他
上一篇:【C語言開源庫】在CLion上使用一個輕量的適合嵌入式系統的環形緩沖庫ring buffer 和C語言Unity單元測驗框架
下一篇:C++掃雷小游戲(附贈源代碼)
