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 方法中,确保在场景销毁时停止线程,以避免在不再需要时继续浪费资源。

相关推荐
2395730491 小时前
Avalonia 12 代码编辑器性能横评:TKCode.Arc CodeEditor vs AvaloniaEdit 12.0(含深度调优实战)
c#·.net·avalonia·codeeditor·tkcode.arc
ttod_qzstudio6 小时前
系统架构设计师论文逐句拆解(三):ATAM 架构评估,怎样把“方案比较”写成质量属性权衡
unity·架构·系统架构·软考
小贺儿开发1 天前
Unity 轻量级外部素材加载器(热更新)
科技·学习·unity·程序员·工具·热更新·ugui
张人玉2 天前
C#如何使用FreeSql连接数据库
数据库·c#·freesql
吴可可1233 天前
C#打断多段线实现方法
c#
Kari113 天前
医药和制造行业的外文文档批量翻译,排版怎么保住?
开发语言·c#·制造
Warson_L3 天前
.NET 8 速成笔记 1:用 VS Code 做 C# / .NET 开发
c#·.net
Warson_L3 天前
.NET 8 速成笔记 9:C# 项目常见场景(基础设施篇)
c#·.net
Warson_L3 天前
.NET 8 速成笔记 8:C# 项目常见业务场景与写法(数据与业务篇)
c#·.net
Warson_L3 天前
.NET 8 速成笔记 3:作业清单
c#·.net