简单的使用方法
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);
}
}
就这样。自己看吧