So I’ve seen some people asking how you would go about downloading executable code from an external location, reading it into memory and executing it in ones running application.
Now some readers might go “eh? why the heck would someone want to do that?”. Well first off, its cool™, but seeing as that is rarely an argument which convinces decision makers, here’s a few others:
Patching. The ability to modify the behaviour of your downloaded executable after distribution, without requiring re-download.
Highly dynamic online content. Say you’re building a virtual world or something. You might want to have the ability to add more complex behaviours to downloaded content – more than what a data-driven approach allows for.
Or how about expanding the capabilities of user generated content?
There. Those are my alibis and I’m sticking to them.
Now this example is quick and simple so as to not bloat the post too much. Regardless of your use, you’ll likely be wanting to add in for instance some cache functionality for real-world use.
Right. So this example contains three pieces of eight, uh, code:
The loader utility – responsible for downloading and making available the remote code.
The assembly – you know, the one we’re downloading.
An example handler. For easy re-use, I’ve designed this example to allow for easy re-use of the loader utility by externalising handling of the assemblies via messages. This example handler shows some techniques for accessing the data of loaded assemblies.
Using the example:
Download and save /Assets/WWWAssemblyLoader.cs, /Assets/NewBehaviourScript.cs and /MyAssembly.cs.
Download and install the mono runtime (or the .net equivalent on Windnows – not tested, but should work just fine).
Build the assembly from the terminal – using the build command supplied at the end of this post.
Upload the assembly to some host (save the URL for later).
Open up your Unity project.
Add the WWWAssemblyLoader and NewBehaviourScript scripts to a GameObject and set the URL property of the first to that of your uploaded assembly.