Thread ending prematurely?

I’m developing a game that generates procedural terrain in 32x32 chunks. To prevent slight freezes in the game as the player moves around I’m trying to move the terrain calculations to their own thread. Once that threads completes, the main Unity thread takes over and generates the terrain mesh. The code works fine when everything runs in the main thread aside from the slight freezes. When I move the terrain generation code to it’s own thread however, sometimes I’ll get a complete 32x32 chunk created but most of the time I only get a small piece of the chunk created. Is there something about threading that I’m not taking into account here?

Update
The problem was the method that was creating the thread was ending before the thread could complete. I added “while (thread.IsAlive) Thread.Sleep(1)” to the code and that solved the problem however it introduced the problem of having the main thread sleep which defeats the purpose of what I’m trying to do. Guess I’ll have to try a different route.

I had similar issue. It turned out that there was an exception but it wasn’t printing to console due to not being main thread (throw-ing on worker thread manually will print nothing as well).

This is what helped - nesting your code inside try/catch block with Debug.LogException:

Thread thread = new Thread(
    ()=> {
        try {
            /*

            Your actual code goes here

            */
        } catch (System.Exception ex) {
            Debug.LogException(ex);
        }
    }
);

You can easily solve this problem: Don’t wait with Thread.Sleep, but by waiting frame after frame:

void Update()
{
  if(!workerThread.IsAlive)
  {
    DoAThing();
  }
}

Or even better: Use a coroutine. Feel free to use this class of mine like this:

void Start()
{
  StartCoroutine(MyCoroutine());
}

IEnumerator MyCoroutine()
{
  yield return new CoroutineThread(() =>
  {
    // Threaded stuff here
  });
  // Stuff after thread has finished here
}