Last active
November 20, 2021 13:47
-
-
Save yamanyar/95a2f42b5c984aef9860 to your computer and use it in GitHub Desktop.
Unity: Creating a Thread and Making Callback Called by UI Thread
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
delegate void JobResultHandler(bool result); | |
public static void DoJobAsync (string someParameter, JobResultHandler jobResultHandler = null) | |
{ | |
//If callback is null; we do not need unity adapter, otherwise we need to create it in ui thread. | |
ThreadAdapter adapter = jobResultHandler == null ? null : CreateUnityAdapter (); | |
System.Threading.ThreadPool.QueueUserWorkItem ( | |
//jobResultHandler is a function reference; which will be called by UIThread with result data | |
new System.Threading.WaitCallback (ExecuteJob),new object[] { someParameter,adapter,jobResultHandler}); | |
} | |
private static void ExecuteJob (object state) | |
{ | |
object[] array = state as object[]; | |
string someParameter = (string)array [0]; | |
ThreadAdapter adapter =array [1] as ThreadAdapter; | |
JobResultHandler callback =array [2] as JobResultHandler; | |
//... time consuming job is performed here... | |
bool result = ComplexJob (someParameter); | |
//if adapter is not null; callback is also not null. | |
if (adapter != null) { | |
adapter.ExecuteOnUi (delegate { | |
callback (result); | |
}); | |
} | |
} | |
/// <summary> | |
/// Must be called from an ui thread | |
/// </summary> | |
/// <returns>The unity adapter.</returns> | |
internal static ThreadAdapter CreateUnityAdapter () | |
{ | |
GameObject gameObject = new GameObject (); | |
return gameObject.AddComponent<ThreadAdapter> (); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal class ThreadAdapter : MonoBehaviour { | |
private volatile bool waitCall = true; | |
public static int x = 0; | |
//this will hold the reference to delegate which will be | |
//executed on ui thread | |
private volatile Action theAction; | |
public void Awake() { | |
DontDestroyOnLoad (gameObject); | |
this.name = "ThreadAdapter-" + (x++); | |
} | |
public IEnumerator Start() { | |
while (waitCall) { | |
yield return new WaitForSeconds(.05f); | |
} | |
theAction (); | |
Destroy (gameObject); | |
} | |
public void ExecuteOnUi (Action action) | |
{ | |
this.theAction = action; | |
waitCall = false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment