Last active
March 21, 2018 01:17
-
-
Save Rallymen007/5354983d43d02de1387e to your computer and use it in GitHub Desktop.
Compile C# code in standalone Unity http://answers.unity3d.com/questions/364580/scripting-works-in-editor-try-it-but-not-build.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void GenerateCSharpCode(CodeCompileUnit ccu, string filename) | |
{ | |
// Generate the code with the custom C# code provider | |
Modified.Mono.CSharp.CSharpCodeCompiler compiler = new Modified.Mono.CSharp.CSharpCodeCompiler(); | |
// Setup the compilation settings, write a DLL inside the Temp folder | |
CompilerParameters compileOptions = new CompilerParameters(); | |
compileOptions.GenerateInMemory = false; | |
compileOptions.GenerateExecutable = false; | |
compileOptions.CompilerOptions = "/target:library"; | |
compileOptions.OutputAssembly = "Temp/" + Path.GetFileNameWithoutExtension(filename) + ".dll"; | |
// Add all the assembly references so the compilation can succeed (required if dependencies) | |
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { | |
compileOptions.ReferencedAssemblies.Add(assembly.Location); | |
} | |
// Actually compile the code | |
CompilerResults compilerResults = compiler.CompileAssemblyFromDom(compileOptions, ccu); | |
// Print the eventual errors | |
foreach (CompilerError compilerError in compilerResults.Errors) | |
Debug.LogError(compilerError); | |
// Load the compiled assembly in memory | |
System.Reflection.Assembly.LoadFrom(compilerResults.CompiledAssembly.Location); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment