Unity 에서 Threading 과 협동 프로그램 이 공동으로 사용 하 는 간단 한 방법

2696 단어 unity3D
간단 한 사용법
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(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 + "
Assets URL: " + config.AssetsUrl); } }

단독 클래스 관리 만 들 기
using System;
using System.Threading;
 
/// 
/// A CustomYieldInstruction that executes a task on a new thread and keeps waiting until it's done.
/// http://JacksonDunstan.com/articles/3746
/// 
class WaitForThreadedTask : UnityEngine.CustomYieldInstruction
{
	/// 
	/// If the thread is still running
	/// 
	private bool isRunning;
 
	/// 
	/// Start the task by starting a thread with the given priority. It immediately executes the
	/// given task. When the given task finishes,  returns true.
	/// 
	/// Task to execute in the thread
	/// Priority of the thread to execute the task in
	public WaitForThreadedTask(
		Action task,
		ThreadPriority priority = ThreadPriority.Normal
	)
	{
		isRunning = true;
		new Thread(() => { task(); isRunning = false; }).Start(priority);
	}
 
	/// 
	/// If the coroutine should keep waiting
	/// 
	/// If the thread is still running
	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(json);
		});
		Debug.Log("Version: " + config.Version + "
Assets URL: " + config.AssetsUrl); } }

이렇게.혼자 보 세 요.

좋은 웹페이지 즐겨찾기