Unity中Threading和 协同程序 共同使用的简单方法

简单的使用方法
using System.Collections;
using System.IO;
using System.Threading;
using UnityEngine;
 
public class TestScript : MonoBehaviour
{
	class Config
	{
		public string Version;
		public string AssetsUrl;
	}
 
	void Start()
	{
		StartCoroutine(LoadConfig());
	}
 
	IEnumerator LoadConfig()
	{
		// Start a thread on the first frame
		Config config = null;
		bool done = false;
		new Thread(() => {
			// Load and parse the JSON without worrying about frames
			string json = File.ReadAllText("/path/to/config.json");
			config = JsonUtility.FromJson<Config>(json);
			done = true;
		}).Start();
 
		// Do nothing on each frame until the thread is done
		while (!done)
		{
			yield return null;
		}
 
		// Use the config on the first frame after the thread is done
		Debug.Log("Version: " + config.Version + "\nAssets URL: " + config.AssetsUrl);
	}
}

单独建立个类管理

using System;
using System.Threading;
 
/// <summary>
/// A CustomYieldInstruction that executes a task on a new thread and keeps waiting until it's done.
/// http://JacksonDunstan.com/articles/3746
/// </summary>
class WaitForThreadedTask : UnityEngine.CustomYieldInstruction
{
	/// <summary>
	/// If the thread is still running
	/// </summary>
	private bool isRunning;
 
	/// <summary>
	/// Start the task by starting a thread with the given priority. It immediately executes the
	/// given task. When the given task finishes, <see cref="keepWaiting"/> returns true.
	/// </summary>
	/// <param name="task">Task to execute in the thread</param>
	/// <param name="priority">Priority of the thread to execute the task in</param>
	public WaitForThreadedTask(
		Action task,
		ThreadPriority priority = ThreadPriority.Normal
	)
	{
		isRunning = true;
		new Thread(() => { task(); isRunning = false; }).Start(priority);
	}
 
	/// <summary>
	/// If the coroutine should keep waiting
	/// </summary>
	/// <value>If the thread is still running</value>
	public override bool keepWaiting { get { return isRunning; } }
}

使用方法

using System.Collections;
using System.IO;
using UnityEngine;
 
public class TestScript : MonoBehaviour
{
	class Config
	{
		public string Version;
		public string AssetsUrl;
	}
 
	void Start()
	{
		StartCoroutine(LoadConfig());
	}
 
	IEnumerator LoadConfig()
	{
		Config config = null;
		yield return new WaitForThreadedTask(() => {
			string json = File.ReadAllText("/path/to/config.json");
			config = JsonUtility.FromJson<Config>(json);
		});
		Debug.Log("Version: " + config.Version + "\nAssets URL: " + config.AssetsUrl);
	}
}

就这样。自己看吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值