Controlling Unity Application Through NamedPipe

This article shows how to control scenes on a Unity application by a Windows application with NamedPipe like the following demonstration. The full source is on the GitHub repository.

Windows Side

You can use this IPC class as a NamePipe client to send requests to a Unity application. In the WPF application, a property setter bound to a view sends a request with IPC.Send as follows. IPC.Send waits and returns the response from the player.

Unity Side

In the first place, you must change Api Compatibility Level to .NET 4.x in Player Settings to make NamedPipe available. NamePipe works on the Unity editor's play mode even in .NET Standard 2.0, but it results in an error on a standalone player.

You can use this IPC class as a NamedPipe server to receive requests from a Windows application. The following is the implementation of IPC.Receive to wait for connections from a Windows application.

This is an asynchronous method implemented with UniTask. UniTask is much easier than coroutines to implement asynchronous operations. This method uses synchronous methods of NamedPipe because Unity doesn't implement the asynchronous versions. They don't cause any errors in compilation but result in errors at runtime.

The following Controller class processes requests from the Windows application. You have to put an empty GameObject on every scene and attach a Controller object to the GameObject.

Awake invokes DontDestroyOnLoad not to destroy the Controller on a scene change. Otherwise, the Controller can't send the response for a scene change request after LoadScene. Start invokes IPC.Run with a request handler to start receiving requests.

OnDisable invokes IPC.Close of which implementation is shown below. The method immediately returns on the scene change, in which case the pipe is connected.

Otherwise, it connects its own NamedPipe to stop IPC.Receive waiting for connections. When the code runs on the editor's play mode, if not doing so, a waiting thread leaves on the editor and freezes it on terminating and reloading code.

I originally implemented the above IPC classes. Some articles are showing how to use NamedPipe on Unity. But they are just experimentations and not appropriate to use in real applications. So I Implemented them.

Leave a Reply

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