unity在线程中修改UI的方法
·
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
public class thread_test : MonoBehaviour
{
bool shouldStop = false;
Text text_log;
// 用于同步主线程的上下文
private SynchronizationContext mainThreadContext; //===========定义===============
// Start is called before the first frame update
void Start()
{
text_log = GameObject.Find("Text_log").GetComponent<Text>();
text_log.text = "哈哈哈";
mainThreadContext = SynchronizationContext.Current; //============获取=================
// 主线程开始执行
Thread thread = new Thread(thread_run);
thread.IsBackground = true;
thread.Start();
}
private void thread_run(object obj)
{
int i = 0;
int x = 0;
while (!shouldStop)
{
// 切换到主线程执行
//mainThreadContext.Post( gaitext, i++); //===========第一种方法===========
mainThreadContext.Post((state) => //===========第二种方法===========
{
int index = i++;
// 处理逻辑
text_log.text = "我是子线程," + i.ToString();
Debug.Log("state:" + state);
}, null);
// 使用 Post 方法异步调度任务
mainThreadContext.Post(state => //=============================
{
int index = (int)state;
Debug.Log($"Index: {index} on thread: {Thread.CurrentThread.ManagedThreadId}");
// 处理逻辑
}, ++x);
Debug.Log("Post method called, this line will execute immediately");
Thread.Sleep(1000);
}
}
private void gaitext(object state)
{
// int i = (int)state;
// text_log.text = "我是子线程," + i.ToString();
}
// Update is called once per frame
void Update()
{
}
void OnDestroy()
{
// 在对象销毁时通知线程停止
shouldStop = true;
// if (workerThread != null && workerThread.IsAlive)
// {
// // 等待线程完成
// workerThread.Join(1000); // 等待最多1秒
// }
}
}
记录一下,后面好用
更多推荐


所有评论(0)