Unity多线程简单示例

csharp 复制代码
using UnityEngine;
using System.Threading;

public class texxxst : MonoBehaviour
{
    Thread thread;

    void Start()
    {
        // 创建一个新的线程,并传入要执行的方法
        thread = new Thread(new ThreadStart(DoWork));
        // 启动线程
        thread.Start();
    }

    void DoWork()
    {
        for (int i = 0; i < 10; i++)
        {
            Debug.Log("Thread:" + i);
            //暂停线程一段时间
            Thread.Sleep(1000); // 暂停1秒
        }
    }


    void OnDestroy()
    {
        // 在场景销毁时停止线程
        if(thread != null && thread.IsAlive)
        {
            thread.Abort();
        }
    }

}

首先创建了一个 ThreadExample 类来管理线程。在 Start 方法中创建了一个新的线程,并传入 DoWork 方法作为要执行的任务。然后启动线程,使其开始执行任务。

在 DoWork 方法中编写了线程需要执行的任务。在这个示例中简单地使用循环来输出一些日志,并使用 Thread.Sleep 方法暂停线程一段时间。

在 OnDestroy 方法中,确保在场景销毁时停止线程,以避免在不再需要时继续浪费资源。

相关推荐
吃一碗粉只付一碗钱14 小时前
10-令牌里的用户主键不要明文
服务器·数据库·sql·sqlserver·c#
Oiiouui15 小时前
Godot-GridGame架构DI容器全局联动设计
架构·游戏引擎·godot
胖纸不争17 小时前
EnergyStarZ:让 Windows 后台进程给前台让路的能效管理器(v1.2 发布)
windows·性能优化·c#·win32·ef core
曹牧18 小时前
C#:The operation has timed out
开发语言·c#
He BianGu18 小时前
【WPF-Control教程】IOC 依赖注入
c#·wpf·wpf-control
He BianGu18 小时前
【WPF-Control教程】H.Extensions.Behvaiors 开发文档
c#·wpf·wpf-control
He BianGu19 小时前
【WPF-Control教程】H.Style 开发文档
c#·wpf·wpf-control
He BianGu19 小时前
【WPF-Control教程】MVVM 二次开发文档
c#·wpf·wpf-control
He BianGu19 小时前
【WPF-Control教程】Theme 主题系统二次开发文档
c#·wpf·wpf-control
iCxhust20 小时前
C#双时区时钟设计
开发语言·c#