Profiling Multithreaded Unity3d Applications

You can download the entire set of Unity assets I used for this post from BitBucket: https://bitbucket.org/amesgames/multithreaded-profiling-in-unity. I used Unity 5.3.5 to develop and test the sample scenes and code.

Introduction

Hello and welcome to the first software development blog post I have written in a while. This article kicks off my new website with relevant software development challenges that programmers are facing today. Along with the challenges you will also find solutions that can help inform your current and future software projects.

Problem

Recently, I have been spending time in the Unity game engine. Very early on, it became clear that my applications needed to make use of multiple threads in order to achieve their target frame rate. Any computer your Unity application will run on likely has two or more CPU cores. However, all of the Unity MonoBehaviour scripts in a scene run only on the main thread.

Equipped with some knowledge of the C# System.Threading library, you will have no trouble running parts of your Unity application in a thread other than the main thread, so long as you are not directly calling into the Unity APIs or directly accessing GameObjects or their Components.

However, the built-in profiler that comes with the editor has no way of showing what is occurring on these other threads. In fact, making calls to UnityEngine.Profiler.BeginSample or UnityEngine.Profiler.EndSample from threads other than the main thread will generate an exception.

Run the following MonoBehaviour script to see the runtime exception.

using System.Threading;
 
using UnityEngine;
 
namespace Amesgames.Behaviours
{
	public class UnityProfilerExceptionBehaviour : MonoBehaviour
	{
		void Start()
		{
			new Thread(new ThreadStart(Work)).Start();
		}
 
		void Work()
		{
			UnityEngine.Profiler.BeginSample("test");
			UnityEngine.Profiler.EndSample();
		}
	}
}

In this article, I will describe a solution to these problems. I assume that you already have a basic understanding of multi-threading and synchronization patterns. For a comprehensive survey of synchronization patterns in C#, see this tutorial on Threading in C#.

Let’s begin.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.