Tuesday, January 11, 2011

Asynchronous Unity3D Components.

If you're using async callbacks in .Net, you need a safe way to get those callbacks to modify things inside your Unity engine.

Inherit from this class, then use ScheduleCallback to schedule an anonymous function which will run in the main Unity thread. Problem solved!

using UnityEngine;
using System.Collections;
using System.Collections.Generic;



public class AsyncComponent : MonoBehaviour
{
public delegate void Anonymous ();
List callbacks = new List ();

public virtual void Update ()
{
Anonymous[] c;
lock(this) {
c = callbacks.ToArray();
callbacks.Clear();
}
foreach(var i in c) i();
}

public void ScheduleCallback(Anonymous fn) {
lock(this) {
callbacks.Add(fn);
}
}
}

No comments:

Popular Posts