Unity下的多线程研究

效果:

1.Unity支持多线程的,只要线程不关闭,就一直运行。

2.编辑器模式下,如果线程不关闭,不管是切后台,还是当前场景关闭了,该线程都一直运行。

3.记得销毁线程。

命名空间:

using System.Threading;

1.开启线程

        ThreadStart childRef = new ThreadStart(ThreadTest1);
        childThread = new Thread(childRef);
        childThread.Start();

2。关闭线程

    public void CloseThread()
    {
        if (childThread != null)
        {
            childThread.Abort();
        }
    }

完整代码如下:

using System.Threading;
using UnityEngine;

public class TestThread : MonoBehaviour
{
    static int add_value = 1;
    Thread childThread = null;

    void Start()
    {
        CloseThread();
        ThreadStart childRef = new ThreadStart(ThreadTest1);
        childThread = new Thread(childRef);
        childThread.Start();
    }

    public void ThreadTest1()
    {
        while (true)
        {
            add_value++;
            print("ThreadTest1 is working:"+ add_value);
            Thread.Sleep(1000);
        }
    }

    public void CloseThread()
    {
        if (childThread != null)
        {
            childThread.Abort();
        }
    }


    private void OnDestroy()
    {
        CloseThread();
    }
}

你可能感兴趣的:(unity,c#,游戏引擎,多线程)