Created
April 8, 2011 14:10
-
-
Save anonymous/909908 to your computer and use it in GitHub Desktop.
important parts of a C# scripting setup
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
using Microsoft.CSharp; | |
using System.CodeDom.Compiler; | |
using System.Reflection; | |
namespace MyGameNamespace | |
{ | |
public class ScriptManager | |
{ | |
const string SCRIPT_PATH = "Scripts/"; | |
CodeDomProvider codeProvider; | |
CompilerParameters compilerParams; | |
private void SetUpCompiler() | |
{ | |
codeProvider = new CSharpCodeProvider(); | |
compilerParams = new CompilerParameters(); | |
// compiler settings | |
compilerParams.CompilerOptions = "/target:library"; | |
compilerParams.GenerateExecutable = false; | |
compilerParams.GenerateInMemory = true; | |
compilerParams.IncludeDebugInformation = false; | |
// find libraries on local system | |
string path; | |
path = Assembly.GetAssembly(typeof(Microsoft.Xna.Framework.Game)).Location; | |
compilerParams.ReferencedAssemblies.Add(path); | |
compilerParams.ReferencedAssemblies.Add("MyGame.exe"); | |
} | |
public Script LoadScript(string scriptName) | |
{ | |
Script newScript = new Script(); | |
TextReader textReader = new StreamReader(SCRIPT_PATH + scriptName); | |
try | |
{ | |
// load script text | |
string scriptText; | |
scriptText = textReader.ReadToEnd(); | |
textReader.Close(); | |
// compile into Script object | |
CompilerResults result = codeProvider.CompileAssemblyFromSource(compilerParams, scriptText); | |
if (!result.Errors.HasErrors) | |
{ | |
// get full name of the compiled object | |
string fullName = ""; | |
foreach (Type t in result.CompiledAssembly.GetTypes()) | |
{ | |
fullName = t.FullName; | |
} | |
// if there are no errors, make an instance of the new script object | |
Type type = result.CompiledAssembly.GetType(fullName); | |
newScript = Activator.CreateInstance(type) as Script; | |
} | |
else | |
{ | |
// print compiler errors | |
string errors = ""; | |
foreach (CompilerError ce in result.Errors) | |
{ | |
errors += ce.ToString() + Environment.NewLine + Environment.NewLine; | |
} | |
MessageBox.Show("Compiler error: " + Environment.NewLine + errors); | |
} | |
} | |
catch (Exception ex) | |
{ | |
MessageBox.Show("Script loading error: " + Environment.NewLine + ex.Message); | |
} | |
finally | |
{ | |
textReader.Close(); | |
} | |
return newScript; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment