- Home /
Make persistent background thread in Editor
But when I started testing it, found out that thread has died and started again. Seems, It is related to loading/reloading assamblies before compiling or starting playmode.
But main purpose to save first thread for all time and do not create new one. I've tried to use Scriptableobject, EditorPrefs and static properties, but looks that all these staff is reloaded in editor.
Example of code:
[InitializeOnLoad]
public static class Loader
{
static Loader()
{
Debug.Log("InitializeOnLoad Called");
EditorApplication.update += StartClient;
}
static void StartClient()
{
Debug.Log("StartClient Called");
new TestClient().Start();
}
}
public class TestClient
{
private static string RunKey = "IsRun";
public void Start()
{
Debug.Log("TestClient.Start Called");
if (EditorPrefs.HasKey(RunKey) && EditorPrefs.GetBool(RunKey))
{
Debug.Log("TestClient.Start Called when thread is started");
}
var thread = new Thread(() =>
{
Debug.Log("new Thread started");
while (true)
{
Thread.Sleep(1000);
Debug.Log(string.Format("New Thread {0} still working", Thread.CurrentThread.ManagedThreadId));
}
});
thread.IsBackground = true;
EditorPrefs.SetBool(RunKey, true);
thread.Start();
}
}
Is there any idea how to keep thread persistent?
Answer by Vincent1236 · Jul 12, 2018 at 11:38 AM
Not completely sure, however I believe it might be dying due to unity recompiling all your scripts including this one when you make any script changes as you have mentioned.
Maybe you can try specifying an assembly definition file to prevent it from getting recompiled? Take a look at these Unity Docs on how to get that setup.