突然想到了StartCoroutine,于是使用了下,果然Unity不支持C#提供的多线程,但是可以用自身修改过的StartCoroutine开启,对自己的内部函数目前没看到什么限制,修改后的测试文件代码为
using UnityEngine;
using System.Collections;
using System.Threading;
public class BallInNetTest : MonoBehaviour {
static GameObject[] numberBalls;
static Vector3 fallInNetPos1;
// Use this for initialization
void Start () {
fallInNetPos1 = new Vector3 (-2.757f, 0.748f, 1.347f);
numberBalls = GameObject.FindGameObjectsWithTag("NumberBall");
if (numberBalls.Length != 15)
Debug.Log ("Less than 15 Balls?");
for (int i = 0; i < numberBalls.Length; i++)
{
for (int j = i + 1; j < numberBalls.Length; j++)
{
if(int.Parse(numberBalls[i].name) > int.Parse(numberBalls[j].name))
{
GameObject temp = numberBalls[i];
numberBalls[i] = numberBalls[j];
numberBalls[j] = temp;
}
}
}
}
// Update is called once per frame
public void BallFallInNet()
{
StartCoroutine (WaitAndPrint (2.0F));
for(int i = 0; i < 8;i++)
{
GameObject tmpBall = numberBalls [i];
if (tmpBall != null && tmpBall.activeSelf == true) {
tmpBall.transform.position = fallInNetPos1;
break;
}
}
}
IEnumerator WaitAndPrint(float waitTime) {
int cnt = 3;
while (cnt-- > 0) {
yield return new WaitForSeconds (waitTime);
for (int i = 0; i < 8; i++) {
GameObject tmpBall = numberBalls [i];
if (tmpBall != null && tmpBall.activeSelf == true) {
tmpBall.transform.position = fallInNetPos1;
break;
}
}
}
}
}
这里要注意:
1.StartCoroutine 为MonoBehaviour 成员函数,不能在static中用,所以要把BallFallInNet改成非static函数,调用方式也要改。
2.有StopCoroutine可以停止,但是我们这里选择了简单的例子。其他可以自行研究,具体在Unity中多线程要遵守StartCoroutine的使用方式。