Skip to content

Instantly share code, notes, and snippets.

@robbennet
Created June 4, 2016 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robbennet/b0ad609cb6a61023c900f086020b630d to your computer and use it in GitHub Desktop.
Save robbennet/b0ad609cb6a61023c900f086020b630d to your computer and use it in GitHub Desktop.
Unity3D threading with "anonymous" functions, callbacks, asyc and synchronous methods
using UnityEngine;
public class Example : MonoBehaviour {
void Awake() {
ThreadAction job = new ThreadAction(HeavyLifting);
job.OnComplete += () => { Debug.Log("we're back"); };
job.Start();
StartCoroutine(job.WaitFor()); // asynchronous
DoOtherStuff(); // this will happen immediately
}
void Start() {
StartCoroutine(BlockingJob());
}
IEnumerator BlockingJob() {
ThreadAction job = new ThreadAction(HeavyLifting);
job.OnComplete += () => { Debug.Log("we're back"); };
job.Start();
yield return StartCoroutine(job.WaitFor()); // blocking
DoOtherStuff(); // this will happen once "job" is finished
}
void HeavyLifting() {
int count = 0;
for(int i = 0; i < 10000000000000; i++) {
count += i;
}
Debug.Log(count);
}
void DoOtherStuff() {
Debug.Log("Other stuff");
}
}
using System;
using System.Threading;
using System.Collections;
using UnityEngine;
public class ThreadAction : ThreadedJob {
public bool isRunning = false;
public Action action;
public delegate void HandleComplete();
public event HandleComplete OnComplete;
protected override void ThreadFunction() {
isRunning = true;
if(action != null) {
action();
}
else {
Debug.LogError("Error: Action was null");
}
}
protected override void OnFinished() {
isRunning = false;
if(OnComplete != null) OnComplete();
}
public ThreadAction(Action _action) {
action = _action;
}
}
using System.Threading;
using System.Collections;
public class ThreadedJob {
private bool _isDone = false;
private object _handle = new object();
private System.Threading.Thread _thread = null;
public bool isDone {
get
{
bool tmp;
lock (_handle)
{
tmp = _isDone;
}
return tmp;
}
set
{
lock (_handle)
{
_isDone = value;
}
}
}
public virtual void Start() {
_thread = new System.Threading.Thread(Run);
_thread.Start();
}
public virtual void Abort() {
_thread.Abort();
}
protected virtual void ThreadFunction() { }
protected virtual void OnFinished() { }
public virtual bool Update() {
if (isDone) {
OnFinished();
return true;
}
return false;
}
public IEnumerator WaitFor() {
while(!Update()) {
yield return null;
}
}
private void Run() {
ThreadFunction();
isDone = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment