Rough Notes on Experiments with UWP APIs in the Unity Editor with C++/WinRT

This post is a bunch of rough notes around a discussion that I’ve been having with myself around working with UWP code in Unity when building mixed reality applications for HoloLens. To date, I’ve generally written the code which calls UWP APIs in .NET code and followed the usual practice around it but in recent times I’ve seen folks doing more around implementing their UWP API calls in native code and so I wanted to experiment with that a little myself.

These notes are very rough so please apply a pinch of salt as I may well have got things wrong (it happens frequently) and I’m really just writing down some experiments rather than drawing a particular conclusion.

With those caveats in place…

Background – .NET and .NET Native

I remember coming to .NET in around 2000/2001.

At the time, I had been working as a C/C++ developer for around 10 years and I was deeply sceptical of .NET and the idea of C# as a new programming language and that I might end up running code that was Just-In-Time compiled.

That said, I was also coming off the back of 10 years of shipping code in C/C++ and the various problems around crashes, hangs, leaks, heap fragmentation, mismatched header files, etc. etc. etc. that afflicted the productivity of C/C++.

So, I was sceptical on the one hand but open to new ideas on the other and, over time, my C++ (more than my C) became rusty as I transitioned to C# and the CLR and its CIL.

There’s a bunch of advantages that come to having binaries made up of a ‘Common Intermediate Language’ underpinned by the CLR rather than native code. Off the top of my head, that might include things like;

  • Re-use of components and tooling across programming languages.
  • CIL was typically a lot smaller than native code representation of the same functionality.
  • One binary could support (and potentially optimize for) any end processor architecture by being compiled just-in-time on the device in question rather than ahead-of-time which requires per-architecture binaries and potentially per-processor variant optimisations.

and there are, no doubt, many more.

Like many things, there are also downsides with one being the potential impact on start-up times and, potentially, memory usage (and the ability to share code across processes) as CIL code is loaded for the first time and the methods JITted to a specific process’ memory in order to have runnable code on the target machine.

Consequently, for the longest time there have been a number of attempts to overcome that JITting overhead by doing ahead of time compilation including the fairly early NGEN tool (which brought with it some of its own challenges) and, ultimately, the development of the .NET Native set of technologies.

.NET Native and the UWP Developer

.NET Native had a big impact on the developer targeting the Universal Windows Platform (UWP) because all applications delivered from the Windows store are ultimately built with the .NET native tool-chain and so developers need to build and test with that tool-chain before submitting their app to the Store.

Developers who had got used to the speed with which a .NET application could be built, run and debugged inside of Visual Studio soon learned that building with .NET Native could introduce a longer build time and also that there were rare occasions where the native code didn’t match the .NET code and so one tool-chain could have bugs that another did not exhibit. That could also happen because of the .NET native compiler’s feature to remove ‘unused’ code/metadata which can have an impact on code – e.g. where reflection is involved.

However, here in 2019 those issues are few and far between & .NET Native is just “accepted” as the tool-chain that’s ultimately used to build a developer’s app when it goes to the Windows Store.

I don’t think that developers’ workload has been affected hugely because I suspect that most UWP developers probably still follow the Visual Studio project structure and use the Debug configuration (.NET compiler) to do their builds during development making use of the regular, JITted .NET compiler and reserve the Release configuration (.NET Native compiler) for their final testing. Either way, your code is being compiled by a Microsoft compiler to CIL and by a Microsoft compiler from CIL to x86/x64/ARM.

It’s worth remembering that whether you write C# code or C++ code the debugger is always doing a nice piece of work to translate between the actual code that runs on the processor and the source that you (or someone else) wrote and want to step through getting stack frames, variable evaluation etc. The compiler/linker/debugger work together to make sure that via symbols (or program databases (PDBs)) this process works so seamlessly that, at times, it’s easy to forget how complicated a process it is and we take it for granted across both ‘regular .NET’ and ‘.NET Native’.

So, this workflow is well baked and understood and, personally, I’d got pretty used to it as a .NET/UWP developer and it didn’t really change whether developing for PC or other devices like HoloLens with the possible exception that deployment/debugging is naturally going to take a little more time on a mobile-powered device than on a huge PC.

Unity and the UWP

But then I came to Unity 😊

In Unity, things initially seem the same for a UWP developer. You write your .NET code in the editor, the editor compiles it “on the fly” as you save those code changes and then you can run and debug that code in the editor.

As an aside, the fact that you can attach the .NET debugger to the Unity Editor is (to me) always technically impressive and a huge productivity gain.

When you want to build and deploy, you press the right keystrokes and Unity generates a C# project for you with/without all your C# code in it (based on the “C# Projects” setting) and you are then back into the regular world of UWP development. You have some C# code, you have your debugger and you can build debug (.NET) or release (.NET Native) just like any other UWP app written with .NET.

Unity and .NET Scripting/IL2CPP

That’s true if you’re using the “.NET Scripting backend” in Unity. However, that backend is deprecated as stated in the article that I just linked to and so, really, a modern developer should be using the IL2CPP backend.

That deprecation has implications. For example, if you want to move to using types from .NET Standard 2.0 in your app then you’ll find that Unity’s support for .NET Standard 2.0 lives only in the IL2CPP backend and hasn’t been implemented in the .NET Scripting backend (because it’s deprecated).

2018.2.16f1, UWP, .NET Scripting Backend, .NET Standard 2.0 Build Errors

With the IL2CPP backend, life in the editor continues as before. Unity builds your .NET code, you attach your .NET debugger and you can step through your code. Again, very productive.

However, life outside of the editor changes in that any code compiled to CIL (i.e. scripts plus dependencies) is translated into C++ code by the compiler. The process of how this works is documented here and I think it’s well worth 5m of your time to read through that documentation if you haven’t already.

This has an impact on build times although I’ve found that if you carefully follow the recommendations that Unity makes on this here then you can get some cycles back but it’s still a longer process than it was previously.

Naturally, when Unity now builds what drops out is not a C#/.NET Visual Studio project but, instead, a C++ Visual Studio project. You can then choose the processor architecture and debug/release etc. but you’re compiling C++ code into native code and that C++ represents all the things you wrote along with translations of lots of things that you didn’t write (e.g. lists, dictionaries, etc. etc.). Those compilations times, again, can get a bit long and you get used to watching the C++ compile churn its way through implementations of things like generics, synchronisation primitives, etc.

Just as with .NET Native, Unity’s C#->C++ translation has the advantage of stripping out things which aren’t used which can impact technologies like reflection and, just like .NET Native, Unity has a way of dealing with that as detailed here.

When it comes to debugging that code, you have two choices. You can either;

  • Debug it at the C# level.
  • Debug the generated C++.
  • Ok, ok, if you’re hardcore you can just debug the assembly but I’ll assume you don’t want to be doing this all the time (although I’ll admit that I did single step some pieces while trying to fix things for this post but it’s more by necessity than choice).

C# debugging involves setting the “Development Build” and “Script Debugging” options as described here and you essentially run up the app on the target device with this debugging support switched on and then ask the Unity debugger to attach itself to that app similarly to the way in which you ask the Unity debugger to attach to the editor. Because this is done over the network, you also have to ensure that you set certain capabilities in your UWP app manifest (InternetClient, InternetClientServer, PrivateNetworkClientServer).

For the UWP/HoloLens developer, this isn’t without its challenges at the time of writing and I mentioned some of those challenges in this post;

A Simple glTF Viewer for HoloLens

and my friend Joost just wrote a long post about how to get this working;

Debugging C# code with Unity IL2CPP projects running on HoloLens or immersive headsets

and that includes screenshots and provides a great guide. I certainly struggled to get this working when I tried it for the first time around as you can see from the forum thread I started below;

Unity 2018.2.16f1, UWP, IL2CPP, HoloLens RS5 and Managed Debugging Problems.

so a guide is very timely and welcome.

As was the case with .NET Native, of course it’s possible that the code generated by IL2CPP differs in its behavior from the .NET code that now runs inside the editor and so it’s possible to get into “IL2CPP bugs” which can seriously impact your productivity.

C# debugging kind of feels a little “weird” at this point as you stare into the internals of the sausage machine. The process makes it very obvious that what you are debugging is code compiled from a C++ project but you point a debugger at it and step through as though it was a direct compilation of your C# code. It just feels a little odd to me although I think it’s mainly perception as I have long since got over the same feeling around .NET Native and it’s a very similar situation.

Clearly, Unity are doing the right thing with making the symbols line up here which is clever in itself but I feel like there are visible signs of the work going on when it comes to performance of debugging and also some of the capabilities (e.g. variable evaluation etc). However, it works and that’s the main thing 😊

In these situations I’ve often found myself with 2 instances of Visual Studio with one debugging the C# code using the Unity debugger support while the other attached as a native debugger to see if I catch exceptions etc. in the real code. It’s a change to the workflow but it’s do-able.

IL2CPP and the UWP Developer

That said, there’s still a bit of an elephant in the room here in that for the UWP developer there’s an additional challenge to throw into this mix in that the Unity editor always uses Mono which means that it doesn’t understand calls to the UWP API set (or WinRT APIs if you prefer) as described here.

This means that it’s likely that a UWP developer (making UWP API calls) takes more pain here than the average Unity developer as to execute the “UWP specific” parts of their code they need to set aside the editor, hit build to turn .NET into C++ and then hit build in Visual Studio to build that C++ code and then they might need to deploy to a device before being able to debug (either the generated C++ or the original .NET code) that calls into the UWP.

The usual pattern for working with UWP code is detailed on this doc page and involves taking code like that below;

which causes the Unity editor some serious concern because it doesn’t understand Windows.* namespaces;

And so we have to take steps to keep this code away from the editor;

And then this will “work” both in the editor and if we compile it out for UWP through the 2-stage compilation process. Note that the use of MessageDialog here is just an example and probably not a great one because there’s no doubt some built-in support in Unity for displaying a dialog without having to resort to a UWP API.

Calling UWP APIs from the Editor

I’ve been thinking about this situation a lot lately and, again, with sympathy for the level of complexity of what’s going on inside that Unity editor – it does some amazing things in making all of this work cross-platform.

I’d assume that trying to bring WinRT/UWP code directly into that Editor environment is a “tall-order” and I think it stems from the editor running on Mono and there not being underlying support there for COM interop although I could be wrong. Either way, part of me understands why the editor can’t run my UWP code.

On the other hand, the UWP APIs aren’t .NET APIs. They are native code APIs in Windows itself and the Unity editor can happily load up native plugins and execute custom native code and so there’s a part of me wonders whether the editor couldn’t get closer to letting me call UWP APIs.

When I first came to look at this a few years ago, I figured that I might be able to “work around it” by trying to “hide” my UWP code inside some .NET assembly and then try to add that assembly to Unity as a plugin but the docs say that managed plugins can’t consume Windows Runtime APIs.

As far as I know, you can’t have a plugin which is;

  • a WinRT component implemented in .NET or in C++.
  • a .NET component that references WinRT APIs or components.

But you can have a native plugin which makes calls out to WinRT APIs so what does it look like to go down that road?

Unity calling Native code calling UWP APIs

I wondered whether this might be a viable option for a .NET developer given the (fairly) recent arrival of C++/WinRT which seems to make programming the UWP APIs much more accessible than it was in the earlier worlds of WRL and/or C++/CX.

To experiment with that, I continued my earlier example and made a new project in Visual C++ as a plain old “Windows Desktop DLL”.

NB: Much later in this post, I will regret thinking that a “plain old Windows Desktop DLL” is all I’m going to need here but, for a while, I thought I would get away with it.

To that project, I can add includes for C++/WinRT to my stdafx.h as described here;

And I can alter my link options to link with WindowsApp.lib;

And then I can maybe write a little function that’s exported from my DLL;

And the implementation there is C++/WinRT – note that I just use a Uri by declaring one rather than leaping through some weird ceremony to make use of it.

If I drag the DLL that I’ve built into Unity as a plugin then my hope is that I can tell Unity to use the 64-bit version purely for the editor and the 32-bit version purely for the UWP player;

I can then P/Invoke from my Unity script into that exported DLL function as below;

And then I can attach my 2 debuggers to Unity and debug both the managed code and the native code and I’m making calls into the UWP! from the editor and life is good & I don’t have to go through a long build cycle.

Here’s my managed debugger attached to the Unity editor;

And here’s the call being returned from the native debugger also attached to the Unity editor;

and it’s all good.

Now, if only life were quite so simple 😊

Can I do that for every UWP API?

It doesn’t take much to break this in that (e.g.) if I go back to my original example of displaying a message box then it’s not too hard to add an additional header file;

And then I can write some exported function that uses MessageDialog;

and I can import it and call it from a script in Unity;

but it doesn’t work. I get a nasty exception here and I think that’s because I chose MessageDialog as my API to try out here and MessageDialog relies on a CoreWindow and I don’t think I have one in the Unity editor. Choosing a windowing API was probably a bad idea but it’s a good illustration that I’m not likely to magically just get everything working here.

There’s commentary in this blog post around challenges with APIs that depend on a CoreWindow.

What about Package Identity?

What about some other APIs. How about this? If I add the include for Windows.Storage.h;

And then add an exported function (I added a DuplicateString function to take that pain away) to get the name of the local application data folder;

and then interop to it from Unity script;

and then this blows up;

Now, this didn’t exactly surprise me. In fact, the whole reason for calling that API was to cause this problem as I knew it was coming as part of that “UWP context” includes having a package identity and Unity (as a desktop app) doesn’t have a package identity and so it’s not really fair to ask for the app data folder when the application doesn’t have one.

There’s a docs page here about this notion of APIs requiring package identity.

Can the Unity editor have a package identity?

I wondered whether there might be some way to give Unity an identity such that these API calls might work in the editor? I could think of 2 ways.

  1. Package Unity as a UWP application using the desktop bridge technologies.
  2. Somehow ‘fake’ an identity such that from the perspective of the UWP APIs the Unity editor seems to have a package identity.

I didn’t really want to attempt to package up Unity and so I thought I’d try (2) and ended up having to ask around and came up with a form of a hack although I don’t know how far I can go with it.

Via the Invoke-CommandInDesktopPackage PowerShell command it seems it’s possible to execute an application in the “context” or another desktop bridge application.

So, I went ahead and made a new, blank WPF project and then I used the Visual Studio Packaging Project to package it as a UWP application using the bridge and that means that it had “FullTrust” as a capability and I also gave it “broadFileSystemAccess” (just in case).

I built an app package from this and installed it onto my system and then I experimented with running Unity within that app’s context as seen below – Unity here has been invoked inside the package identity of my fake WPF desktop bridge app;

I don’t really know to what extent this might break Unity but, so far, it seems to survive ok and work but I haven’t exactly pushed it.

With Unity running in this UWP context, does my code run any better than before?

Well, firstly, I noticed that Unity no longer seemed to like loading my interop DLL. I tried to narrow this down and haven’t figured it out yet but I found that;

  1. First time, Unity wouldn’t find my interop DLL.
  2. I changed the name to something invalid, forcing Unity to look for that and fail.
  3. I changed the name back to the original name, Unity found it.

I’m unsure on the exact thing that’s going wrong there so I need to return to that but I can still get Unity to load my DLL, I just have to play with the script a little first. But, yes, with a little bit of convincing I can get Unity to make that call;

And what didn’t work without an identity now works when I have one so that’s nice!

The next, natural thing to do might be to read/write some data from/to a file. I thought I’d try a read and to do that I used the co_await syntax to do the async pieces and then used the .get() method to ultimately make it a synchronous process as I wasn’t quite ready to think about calling back across the PInvoke boundary.

And that causes a problem depending on how you invoke it. If I invoke it as below;

Then I get an assertion from somewhere in the C++/WinRT headers telling me (I think) that I have called the get() method on an STA thread. I probably shouldn’t call this method directly from my own thread anyway because the way in which I have written it (with the .get()) call blocks the calling thread so regardless of STA/MTA it’s perhaps a bad idea.

However, if I ignore that assertion, the call does seem to actually work and I get the contents of the file back into the Unity editor as below;

But I suspect that I’m not really meant to ignore the assertion and so I can switch the call to something like;

and the assertion goes away and I can read the file contents 😊

It’s worth stating at this point that I’ve not even thought about how I might try to actually pass some notion of an async operation across the PInvoke boundary here, that needs more thought on my part.

Ok, Call some more APIs…

So far, I’ve called and so I felt like I should try a longer piece of code with a few more API calls in it.

I’ve written a few pieces of code in the past which try to do face detection on frames coming from the camera and I wondered whether I might be able to reproduce that here – maybe write a method which runs until it detects a face in the frames coming from the camera?

I scribbled out some rough code in my DLL;

// Sorry, this shouldn't really be one massive function...
IAsyncOperation<int> InternalFindFaceInDefaultCameraAsync()
	auto facesFound(0);

	auto devices = co_await DeviceInformation::FindAllAsync(DeviceClass::VideoCapture);

	if (devices.Size())
		DeviceInformation deviceInfo(nullptr);

		// We could do better here around choosing a device, we just take
		// the front one or the first one.
		for (auto const& device : devices)
			if ((device.EnclosureLocation().Panel() == Panel::Front))
				deviceInfo = device;
		if ((deviceInfo == nullptr) && devices.Size())
			deviceInfo = *devices.First();
		if (deviceInfo != nullptr)
			MediaCaptureInitializationSettings initSettings;

			MediaCapture capture;
			co_await capture.InitializeAsync(initSettings);

			auto faceDetector = co_await FaceDetector::CreateAsync();
			auto faceDetectorFormat = FaceDetector::GetSupportedBitmapPixelFormats().GetAt(0);

			// We could do better here, we will just take the first frame source and
			// we assume that there will be at least one. 
			auto frameSource = (*capture.FrameSources().First()).Value();
			auto frameReader = co_await capture.CreateFrameReaderAsync(frameSource);

			winrt::slim_mutex mutex;

			handle signal{ CreateEvent(nullptr, true, false, nullptr) };
			auto realSignal = signal.get();

				[&mutex, faceDetector, &facesFound, faceDetectorFormat, realSignal]
			(IMediaFrameReader reader, MediaFrameArrivedEventArgs args) -> IAsyncAction
				// Not sure I need this?
				if (mutex.try_lock())
					auto frame = reader.TryAcquireLatestFrame();

					if (frame != nullptr)
						auto bitmap = frame.VideoMediaFrame().SoftwareBitmap();

						if (bitmap != nullptr)
							if (!FaceDetector::IsBitmapPixelFormatSupported(bitmap.BitmapPixelFormat()))
								bitmap = SoftwareBitmap::Convert(bitmap, faceDetectorFormat);
							auto faceResults = co_await faceDetector.DetectFacesAsync(bitmap);

							if (faceResults.Size())
								// We are done, we found a face.
								facesFound = faceResults.Size();
			co_await frameReader.StartAsync();

			co_await resume_on_signal(signal.get());

			// Q - do I need to remove the event handler or will the destructor do the
			// right thing for me?
			co_await frameReader.StopAsync();

That code is very rough and ready but with an export from the DLL that looks like this;

	__declspec(dllexport) int FindFaceInDefaultCamera()
		int faceCount = InternalFindFaceInDefaultCameraAsync().get();


then I found that I can call it from the editor and, sure enough, the camera lights up on the machine and the code returns that it has detected my face from the camera so that’s using a few UWP classes together to produce a result.

So, I can call into basic APIs (e.g. Uri), I can call into APIs that require package identity (e.g. StorageFile) and I can put together slightly more complex scenarios involving cameras, bitmaps, face detection etc.

It feels like I might largely be able to take this approach to writing some of my UWP code in C++/WinRT and have the same code run both inside of the editor and on the device and debug it in both places and not have to go around longer build times while working it up in the editor.

Back to the device…

I spent a few hours in the Unity editor playing around to get to this point in the post and then I went, built and deployed my code to an actual device and it did not work. Heartbreak 😉

I was getting failures to load my DLL on the device and I quickly put them down to my DLL having dependencies on VC runtime DLLs that didn’t seem to be present. I spent a little bit of time doing a blow-by-blow comparison on the build settings of a ‘UWP DLL’ versus a ‘Windows DLL’ but, in the end, decided I could just build my code once in the context of each.

So, I changed my C++ project such that it contained the original “Windows Desktop DLL” along with a “UWP DLL” and the source code is shared between the two as below;

With that in place, I use the 64-bit “Windows Desktop DLL” in the editor and the 32-bit “UWP DLL” on the device (the ‘player’) and that seems to sort things out for me. Note that both projects build a DLL named NativePlugin.dll.

That said, I’d really wanted to avoid this step and thought I was going to get away with it but I fell at the last hurdle but I’d like to revisit and see if I can take away the ‘double build’ but someone will no doubt tell me what’s going on there.

Wrapping Up

As I said at the start of the post, this is just some rough notes but in making calls out to the few APIs that I’ve tried here I’m left feeling that the next time I have to write some Unity/UWP specific code I might try it out in C++/WinRT first with this PInvoke method that I’ve done here & see how it shapes up as the productivity gain of being able to press ‘Play’ in the editor is huge. Naturally, if that then leads to problems that I haven’t encountered in this post then I can flip back, translate the code back to C# and use the regular “conditional compilation” mechanism.


I’m conscious that I pasted quite a lot of code into this post as bitmaps and that’s not very helpful so I just packaged up my projects onto github over here.

Inside of the code, 2 of the scenarios from this post are included – the code for running facial detection on frames from the camera and the code which writes a file into the UWP app’s local data folder.

I’ve tried that code both in the Unity editor and on a HoloLens device & it seems to work fine in both places.

All mistakes are mine, feel free to feed back and tell me what I’ve done wrong! 🙂

UWP Facial Detection Library

A short post. I took some of the code that I once had in this post around doing face detection using the UWP APIs to do on-device face detection and I built it into a library which I’ve dropped here;

The idea is to have a simple class named FaceWatcher which gets hold of a camera stream, runs face detection on it and fires an event (InFrameFaceCountChanged) whenever it’s view of the number of faces in front of the camera changes.

I built a simple test app to wrap around that and included it in the repo where the code to create a FaceWatcher on a default camera becomes as simple as;

this.faceWatcher = new FaceWatcher(
  new CameraDeviceFinder(
    deviceInformation =>
        return (deviceInformation.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);

and the code to then handle the events when the number of faces changes becomes;

this.cancelTokenSource = new CancellationTokenSource();
this.faceWatcher.InFrameFaceCountChanged += OnFaceCountChanged;

   await this.faceWatcher.CaptureAsync(this.cancelTokenSource.Token);
catch (TaskCanceledException)
  this.faceWatcher.InFrameFaceCountChanged -= this.OnFaceCountChanged;

and the test app supplied simply has buttons for Start/Stop and a TextBlock to display the number of faces on screen.

That’s it – my hope is to couple this with a library which can sit on top of it and use the Cognitive Services facial detection APIs to then run identification such that instead of being able to simply flag how many faces are currently in front of the camera, I can use identification to tag when new faces enter/leave the frame by building a short term memory of the faces that have already been seen.

I think that’s all quite achievable with perhaps the main challenge being the one of figuring out the right time and frequency with which to call that API given that invocation involves an HTTP request which comes with a cost both in terms of the round-trip time and a real financial cost which means that I can only realistically call that type of API so many times per minute/hour.

But that’s for another post…:-)

Hitchhiking the HoloToolkit-Unity, Leg 8–Bit of Fun with a Teleporting Rabbit

NB: The usual blog disclaimer for this site applies to posts around HoloLens. I am not on the HoloLens team. I have no details on HoloLens other than what is on the public web and so what I post here is just from my own experience experimenting with pieces that are publicly available and you should always check out the official developer site for the product documentation.

It’s just before Xmas and I thought I’d have a bit of fun in trying to take the ideas around world anchors that I started to play with here;

Hitchhiking the HoloToolkit-Unity, Leg 5–Baby Steps with World Anchors and Persisting Holograms

and see if I could experiment with anchoring holograms across rooms in my house rather than just anchoring holograms in one room.

Most demos can benefit a lot from the introduction of a rabbit Winking smile and I found this one in the Unity Asset Store going free and so I borrowed him;


and tried to introduce him to the idea of teleporting between platforms that are anchored into real-world space;


I was keen to see if I could put those platforms in different rooms in the real world to see how that works.

I feel like there’s something quite ‘magical’ about taking a hologram in one room and doing something to it such that it appears in another room that I can’t currently see (maybe it’s obscured by a wall, floor, ceiling). An extra bit of magic might be to have multiple users sharing the same rooms and holograms so that two users in separate rooms could send holograms back and forth between them and there’s support in the HoloToolkit for doing that type of sharing (see the ‘Holograms 240’ tutorial here).

Below is a quick recording of the simple demo that I came up with – note that;

  1. The video is fairly low quality.
  2. I’ve chosen to have the spatial mapping grid displayed here as an aid to debugging whereas usually I wouldn’t want to use this type of app with all those grey lines drawn all over the mesh like this and it’s a simple ‘checkbox’ change to switch it off.

How does that look from a Unity/code perspective?

Code Behind the Video

My Unity scene is very simple in that I have installed the HoloToolkit and configured my project, scene and capabilities for Holographic development (including making sure that my app has the capability for ‘Spatial Perception’).

My scene then has 4 things in it;


The camera is just the default camera and the Cursor is the cursor prefab taken from the HoloToolkit as I did in this video and with no modifications made to it.

When it comes to SpatialMapping, I started with the prefab from the toolkit as in this video but then I did some reading about caching and settings and multiple rooms and I found all of these forum posts really useful;

and that last article is so good that I’ll reference it twice;

System’s Spaces vs in-app mapping

but for my scenario I went with what seemed like a fairly simple set-up in that I took the Spatial Mapping prefab;


and I took away the ‘Object Surface Observer’ as it didn’t seem to have a runtime role to play and I then tweaked some parameters down to try and end up with a situation where I was asking for a less complex mesh than the prefab’s setting of 500 triangles per square metre (mine is set to 50) and trying to update it more frequently (1 second versus 3.5 seconds);


and I think that’s all I changed on it although I also edited the material that the wireframe is rendered with to make it more of a grey than a white because I find that so much shiny white mesh can make my head hurt Smile 

Prefabs to Instantiate at Runtime

I made a prefab out of my ‘teleporter’ disk so as to make it an empty game object which contains a box collider and a cylinder and it uses the Hand Draggable script in order that the user can drag it around trying to make sure that it does not turn to face the user but, instead, stays upright;


The intention of the empty game object is to provide a parent object that can be used to reparent the rabbit as it teleports to this particular disk and that seemed to work out reasonably well.

The rabbit works in a very similar way in that it is also a pre-fab and I have attached both a capsule collider and the Hand Draggable script to it as well except this time around I allow it to orientate itself towards the user;


and both of these prefabs also have a script on them called Drag and Collide which really came from my previous blog post where I’d done something very similar with a Xmas present. That script looks like this;

using System;
using HoloToolkit.Unity.InputModule;
using UnityEngine;
using HoloToolkit.Unity;

public class DragAndCollide : MonoBehaviour
  void Start()
    var handDraggable = this.gameObject.GetComponent<HandDraggable>();

    handDraggable.StartedDragging += OnStartedDragging;
    handDraggable.StoppedDragging += OnStoppedDragging;
  void OnStartedDragging()
    // Transporters (not rabbits) have world anchors.
    if (GameState.Instance.IsTransporter(this.gameObject))

    // We add rigid body here if it's not already present. We can't
    // leave it all the time because it's not compatible with
    // world anchors so we can't have both at the same time
    // (AFAIK).
    var rigidBody = this.gameObject.GetComponent<Rigidbody>();

    if (rigidBody == null)
      rigidBody = this.gameObject.AddComponent<Rigidbody>();

      // We don't want our objects to fall to the floor.
      rigidBody.useGravity = false;
  void OnStoppedDragging()
    // We take away the RigidBody because it doesn't play well with
    // world anchor. Can't use DestroyImmediate here because that's
    // not allowed (AFAIK).

    // Empirically, if I try and create the world anchor at this
    // point then I seem to hit a problem whereas if I just set
    // a flag then do it in LateUpdate things seem to work out.
    if (GameState.Instance.IsTransporter(this.gameObject))
      this.gameObjectNeedsAnchoring = true;
  void OnCollisionEnter(Collision collision)
    // If we do get a collision then we (a bit rudely) just stop the
    // drag operation.

    // Did we collide into a transporter?
    if (GameState.Instance.IsTransporter(collision.collider.gameObject) &&
      // Transport!
      GameState.Instance.Transport(this.gameObject, collision.collider.gameObject);
  private void LateUpdate()
    if (this.gameObjectNeedsAnchoring)
      this.gameObjectNeedsAnchoring = false;

  bool gameObjectNeedsAnchoring;

That script is really trying to achieve a few things;

  1. It tries to make sure that the game object has a RigidBody component on it between Start/Stop of drags.
  2. It tries to remove the world anchor from a transporter as it starts being dragged and put it back when it stops being dragged.
  3. It tries to detect collisions between rabbits and transporters and to transport the rabbit when those collisions occur.

This script depends on a script called GameState and you might notice that I’m using what I think of as quite a ‘clunky’ mechanism to try and differentiate in this script between rabbits and transporters using a method GameState.Instance.IsTransporter and this somewhat reflects my collision with Unity and its approach to adding components to objects rather than (e.g.) sub-classing them. I could do a better job than I’m currently doing so this way of doing things does feel a little ‘rough’.

Those are my 2 prefabs and the behaviours on them. I then have a ‘placeholder’ in my scene which does some more work.

The Placeholder and GameState Script

My placeholder has a bunch of scripts associated with it, all but one of which are straight out of the HoloToolkit without any modification to the settings;


in the screenshot, all the red bits are just scripts used without any changes from the toolkit. The blue stuff is where I have added my own script (GameState) and you’d spot that it has two properties for the Transporter Prefab and the Character Prefab (the rabbit) and also that I’ve used the Keyword Manager in order to link the Clean spoken keyword to a GameState.OnClear method.

That GameState script then looks like this;

using HoloToolkit.Unity;
using HoloToolkit.Unity.InputModule;
using UnityEngine;

public class GameState : Singleton<GameState>, IInputClickHandler
  public Transform transporterPrefab;
  public Transform characterPrefab;
  public GameObject TransporterHome
  public GameObject TransporterAway

  public bool IsPlacingTransporters
      return ((this.TransporterHome == null) ||
        (this.TransporterAway == null));
  public bool IsTransporter(GameObject gameObject)
    return ((gameObject == this.TransporterHome) ||
      (gameObject == this.TransporterAway));
  public string GetTransporterName(GameObject gameObject)
    return (gameObject == 
      this.TransporterHome ? transporterHomeName : transporterAwayName);
  public void Transport(GameObject gameObject, GameObject transporter)
    // Are we going 'home' or 'away' ?
    var newTransporter =
      (transporter == this.TransporterHome) ? this.TransporterAway : this.TransporterHome;

    // Reparent the object (rabbit) off the new transporter and move it up in the
    // air a little so that it no longer collides because if it collides then my
    // other code will stop it moving!
    gameObject.transform.localPosition = new Vector3(0, 0.2f, 0);
  void Start()
    // We want to respond to clicks if nothing else handles them.
  private void Update()
    if (!this.loaded && (WorldAnchorManager.Instance.AnchorStore != null))
      var ids = WorldAnchorManager.Instance.AnchorStore.GetAllIds();

      // NB: I'm assuming that the ordering here is either preserved or
      // maybe doesn't matter.
      foreach (var id in ids)
        var instance = Instantiate(this.transporterPrefab);

        WorldAnchorManager.Instance.AttachAnchor(instance.gameObject, id);

        if (id == transporterHomeName)
          this.TransporterHome = instance.gameObject;
          this.TransporterAway = instance.gameObject;
      this.loaded = true;
  public void OnInputClicked(InputEventData eventData)
    // Are we making a transporter or a rabbit?
    var prefab = 
      this.IsPlacingTransporters ? this.transporterPrefab : this.characterPrefab;

    var instance = Instantiate(prefab);

    // Initially, parent the object off the placeholder.

    // Try to put it 2m in front of the user (which might cause it to collide which would
    // be 'bad' 😦 ).
    instance.gameObject.transform.position =
      GazeManager.Instance.GazeOrigin +
      GazeManager.Instance.GazeNormal * 2.0f;

    if (!this.IsPlacingTransporters)
      instance.gameObject.transform.forward = GazeManager.Instance.GazeNormal;
      if (this.TransporterHome == null)
        this.TransporterHome = instance.gameObject;
        this.TransporterAway = instance.gameObject;
  public void OnClear()
    foreach (Transform child in this.transform)
      // Only transporters have world anchors so remove those here.
      if (this.IsTransporter(child.gameObject))
  bool loaded;
  const string transporterHomeName = "home";
  const string transporterAwayName = "away";

and while that code might be a little bit ‘clumsy’, I don’t think there’s too much in there that shouldn’t be fairly obvious in terms of what it’s doing and the code around loading world anchors is something that I’ve re-used from a previous blog post.

I think it’s fairly clear that the way in which I’m identifying my 2 transporter objects is pretty clunky and there’s perhaps a need for some other classes to manage (e.g.) the world anchors but this was my first rough sketch to try and get what I wanted working.

Wrapping Up

I quite enjoyed playing with this scenario – I wanted to see how well world anchors work for me across more than one room and they turned out to work very well indeed and I learned a few things (mostly from the forums) along the way so it was useful and I also got a rabbit that could teleport Winking smile