One of my most useful tools has always been the WorkerThread class, and although not really relevant to anything in TNet itself, I decided to include it in the package in case you too find it useful.
In simplest terms, it's a thread pool that's really easy to use.
WorkerThread.Create(delegate ()
{
// Do something here that takes up a lot of time
},
delegate ()
{
Debug.Log("Worker thread finished its long operation!");
});
In the code above, the first delegate is going to be executed on one of the worker threads created by the WorkerThread class. The class will automatically create several, and will reuse them for all of your future jobs. As such, there are no memory allocations happening at run-time. The second delegate is optional, and will execute on the main thread (in the Update() function) when the first delegate has completed its execution.
This dual delegate approach trivializes creation of complex jobs. To pass arguments, you can simply take advantage of how anonymous delegates work. For example this code will take the current terrain and flip it upside-down:
var td = Terrain.activeTerrain.terrainData;
var size = td.heightmapResolution;
var heightmap = td.GetHeights(0, 0, size, size);
WorkerThread.Create(delegate ()
{
for (int y = 0; y < size; ++y)
{
for (int x = 0; x < size; ++x)
{
heightmap[y, x] = 1f - heightmap[y, x];
}
}
},
delegate ()
{
td.SetHeights(0, 0, heightmap);
});
The worker thread class will work both at run time and edit time, but edit time means it will execute both delegates right away. Currently the project I'm working on uses WorkerThread everywhere -- from ocean height sampling, to merging trees, to generating procedural terrain and textures.
Questions? Ask away.