不要在协程里做耗时的工作,会卡住整个游戏
2019-08-12 本文已影响0人
jojo911
以下是测试代码,分别用线程和协程实现
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
public class CoroutinTest : MonoBehaviour
{
public Text t;
int m_Count = 0;
float m_second = 0;
// Use this for initialization
void Start ()
{
//StartCoroutine(CoroutineTest());
new Thread(new ThreadStart(SubThread)).Start();
}
private void Update()
{
t.text = m_Count.ToString() + " " + m_second;
}
void SubThread()
{
while (true)
{
Thread.Sleep(1000);
string strFile = "E:/MyTest/Unity2017/Assets/ColoutineTest.txt";
//Debug.Log(string.Format("begin time : {0}", System.DateTime.Now.ToString("T")));
long tmp = System.DateTime.Now.Ticks;
for (int i = 0; i < 100; i++)
{
byte[] b = File.ReadAllBytes(strFile);
}
m_second = (System.DateTime.Now.Ticks - tmp) / 1000000;
//Debug.Log(string.Format("end time : {0}", System.DateTime.Now.ToString("T")));
m_Count++;
}
}
IEnumerator CoroutineTest()
{
while (true)
{
yield return new WaitForSeconds(1f);
string strFile = "E:/MyTest/Unity2017/Assets/ColoutineTest.txt";
Debug.Log(string.Format("begin time : {0}", System.DateTime.Now.ToString("T")));
long tmp = System.DateTime.Now.Ticks;
for (int i = 0; i < 100; i++)
{
byte[] b = File.ReadAllBytes(strFile);
}
m_second = (System.DateTime.Now.Ticks - tmp) / 1000000;
Debug.Log(string.Format("end time : {0} tick:{1}", System.DateTime.Now.ToString("T"), m_second));
m_Count++;
}
}
}