Quantcast
Channel: Questions in topic: "assemblies"
Viewing all articles
Browse latest Browse all 145

Using Dynamically Generated Assemblies for Mods

$
0
0
So, I have this nifty code in my Unity project: using System; using System.Reflection; using System.CodeDom.Compiler; using System.Collections.Generic; using System.IO; using UnityEngine; public class ModLoader { private List mods; public IReadOnlyList Mods { get { return mods.AsReadOnly(); } } public ModLoader() { mods = new List(); LoadMod("mod.txt"); Debug.Log(mods[0].ModAssembly.GetType("ModData").GetField("modName").GetValue(null)); Debug.Log(mods[0].ModAssembly.GetType("ModData").GetMethod("Str").Invoke(null, BindingFlags.Static, null, null, null)); mods[0].ModAssembly.GetType("ModData").GetMethod("Run").Invoke(null, BindingFlags.Static, null, null, null); } public void LoadMod(string filePath) { if (mods.Count >= 999) { Debug.LogError("Cannot load mod. Max mods loaded (999)."); return; } string generatedName = "ModAssembly" + (mods.Count < 10 ? "00" : (mods.Count < 100 ? "0" : "")) + mods.Count + ".dll"; filePath = (Application.dataPath + @"\Mods" + ((filePath.Replace("/", @"\"))[0] == '/' ? "" : "/")).Replace("/", @"\") + filePath; Debug.Log("Generated Name: " + generatedName + " File Path: " + filePath); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = false; parameters.GenerateInMemory = true; parameters.OutputAssembly = generatedName; CompilerResults r = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromFile(parameters, filePath); mods.Add(new Mod(Assembly.LoadFrom(generatedName), "test")); File.Delete(Directory.GetParent(Application.dataPath) + @"\" + generatedName); } } and as you can see, in the constructor I use the LoadMod method. The source of the file it uses is: public class ModData { public static string modName = "Super kool mod"; public static string modVersion = "1.2.1"; public static void Run() { } public static string Str() { return "This is generated! :3"; } } And, that all works as expected. The console will read: "Super kool mod", then "This is generated! :3". My question is: is it possible to access anything from my current project from that code that is loaded? I'm thinking that mods with full control could be really beneficial. Of course, I would have to do a kind-of scan to make sure it does not do anything malicious. Anyway, that's aside the point. If I try to add using UnityEngine; in the loaded code, I get this error: FileNotFoundException. Now, is there anywhere I can place the UnityEngine.dll so that it can be found? Is what I am trying to do possible? I think it is not, but I figured I would try and ask before giving up hope.

Viewing all articles
Browse latest Browse all 145

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>