我的工程-关于测试程序的多线程

突然想到了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的使用方式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值