Automatic F# Compilation in Unity

I was playing around with F# and Unity integration and there are some nice examples out there  but they all relied on compilation systems outside of Unity, build some .dll in Xamarin then drop it into a Unity project.  Cool, but it’s not usable if we don’t hook into Unity’s build system and get a fresh build every time we edit a .fs file.  So, I decided to explore doing just that with UnityEditor.AssetPostprocessor.  When you implement a AssetPostprocessor you get called with a message every time you reimport an Asset.  This happens when the file gets touched on disk.  So what we can do with AssetPostprocessor is recompile a .dll full of F# code whenever a dependent F# file is edited.

Here is example code of that method:

In order to actually use this you’ll need to build a target in MonoDevelop for a .dll that will contain this AssetPostprocessor.  Put that .dll in your project’s Assets.  You’ll also have to make sure that your Unity project has FSharp.Core.dll as an Asset if you want to use your F# code.  I had luck using version 2.3.0.  You can check the version with “monodis –assembly <path to dll>”.  The build rule will have to be made a bit more robust if you wanted to compile something with a more complex dependency tree of course.  If you need help making MonoBehaviours in F#, this will help.

Sorry I didn’t didn’t post this on Github.  There is a considerable amount of work to make this idea handle most cases.  It served my purpose as is, maybe I’ll package it up later.

Leave a Reply

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