A word of warning. This is loosely Unity related.
I’m trying to create an editor system where I can create code from a string and save it to .cs file. (It sounds strange, but I have this idea…) I have an editor script, and it doesn’t log any errors right now, but when I run it, I don’t have any code. I tried several things.
-
Using a binary formatter to serialize my CompilerResults into binary then putting that into a FileStream. This created a .cs file in the right spot, but it was empty.
-
Here’s what I’m currently doing. I’m open to any changes.
using UnityEngine;
using System.CodeDom.Compiler;
using System.IO;
using UnityEditor;
using Microsoft.CSharp;
public class TestWriteFiles : ScriptableWizard {
private int i;
public string[] st = new string[1];
[MenuItem ("GameObject/Write File")]
static void CreateScript ()
{
string code = "";
code += "using UnityEngine;";
code += "public class CSTest : MonoBehaviour {";
code += " //Use this for initialization.";
code += " public void Start () {";
code += " }";
code += "}";
string assetPath = "Script.cs"; //What should this be?
//Is it relative, absolute?
if (File.Exists(assetPath))
{
File.Delete(assetPath); //Delete anything at that location
}
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
//I think that's right
// Set up parameters for the compilation:
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = false;
parameters.OutputAssembly = assetPath;
parameters.TempFiles = new TempFileCollection(".", true);
//This creats a default named file in the project folder that contains
//what I want with some arbitrary numbers and letters for a name, I just don't have any more control than that over it.
//right folder.
CompilerResults cR = provider.CompileAssemblyFromSource(parameters, code);
Debug.Log("Compiled");
}
}
Any help is greatly appreciated. ![]()