1. 程式人生 > 其它 >[Unity][C#]多執行緒使用

[Unity][C#]多執行緒使用

多執行緒的使用

執行緒裡面不能含有Unity元件等,只能 用於一些 純C#程式碼( 數值、類的計算,初始化)

...
using System.Threading;
...
void Start()
    {
    ...
        ThreadStart ref = new ThreadStart(testThread);
        Thread thread = new Thread(ref);
        thread.Start();
    ...
    }
...
 private void testThread()
    {
        int num1 = 1000, num2 = 100;
        for (int i = 0; i < num1; i++)
        {
        ...
            for (int j = 0; j < num2; j++)
            {
            ...
            }//
        ...
        }//
    }//
...


測試打包後能否正常使用

using UnityEngine;
using System.Threading;
using UnityEngine.UI;

public class TestThread : MonoBehaviour
{
    public string str = "";
    public Text text;
    bool threadDone = false;

    // Start is called before the first frame update
    void Start()
    {
        ThreadStart childRef = new ThreadStart(testThread);
        Thread childThread = new Thread(childRef);
        childThread.Start();
    }//

    private void Update()
    {
        if (threadDone
            && text)
        {
            text.text = str;
        }//
        else return;
    }//

    private void testThread()
    {
        //6400個小格子
        for (int i = 0; i < 2; i++)//從x = 0開始
        {
            for (int j = 0; j < 10; j++)
            {
                str = str+ ".j:" + j;
            }//
            str = str+"///i:"+i+"///";
        }//
        threadDone = true;
    }//
}//

PC打包

安卓打包