2016-12-21

Preventing Unity3D IL2CPP from stripping your code

I was trying to get a list of a type's constructors at runtime using reflection, so that I could create an instance of the class using dependency injection.

All worked just fine until we tried to build the app for iOS. At first we were using Mono as the scripting back-end, but it seems that new versions of iOS pop up a dialog telling the user the app is 32 bit and may run slowly (i.e. "Your app is crap"). When switching the backend scripting to IL2CPP (in File->Builder->Player Settings) the app suddenly wasn't working. It turns out that SomeType.GetConstructors().Count was returning zero, which was a problem because obviously I wanted to invoke those constructors with dependencies.

The problem was that because these constructors weren't being calling explicitly from anywhere in my app IL2CPP decided I didn't need them, and stripped them out.

The solution is to create a file in your Assets folder called link.xml and fill it in like so....

<linker>
  <assembly fullname="Assembly-CSharp">
    <type fullname="Holovis.*" preserve="all"></type>
  </assembly>
</linker>

Assembly-CSharp is the default name created for all of your scripts by Unity. If you are using any others you need to prevent stripping on then you can add additional <assembly> nodes. As you can see from the example you can list types individually or use * as a wild card.  You can have multiple <type> nodes per <assembly> node.

Read this page from the manual for more information.

No comments: