- Home /
use of EditorUtility.CompileCSharp
Hello,
I am working on an Editor script to
create an new C# script with a new class name which is inherited from MonoBehavior, and save it on disk. The script should be copied from an existing script, MyScriptTemplate.cs, but the class name and script file name should be renamed as MyNewScript.cs
create an empty gameobject, MyNewGameObject
add (attach) the newly created c# script, MyNewScript.cs, to MyNewGameObject as a component
Here is the code:
[MenuItem("GameObject/Create Other/MyGameObject")]
static void CreateNewMyGameObject()
{
string source = "Assets/MyScripts/MyScriptTemplate.cs";
string target = Application.dataPath + "/MyNewScript.cs";
MonoScript s = AssetDatabase.LoadAssetAtPath(source, typeof(MonoScript)) as MonoScript;
string scriptContent = Regex.Replace(s.text, "MyScriptTemplate", "MyNewScript");
StreamWriter sw;
using (sw = File.CreateText(target))
{
sw.Write(scriptContent);
}
AssetDatabase.ImportAsset(target);
AssetDatabase.Refresh();
//EditorUtility.CompileCSharp(string[] sources, string[] references, string[] defines, string outputFile);//how to specify the parameters?
GameObject aNewGameObject = new GameObject("MyNewGameObject");
//aNewGameObject.AddComponent<MyNewScript>();//this is not working because template parameters should be determined at compile time
aNewGameObject.AddComponent("MyNewScript");
}
With this sample code, both step 1 and step 2 are working correctly. However, MyNewScript cannot be attached to MyNewGameObject as a component, and there is a warning message: "Script MyNewScript has not finished compilation yet. Please wait until compilation of the script has finished and try again."
I am not sure if EditorUtility.CompileCSharp() is the correct method to solve this problem. If it is, how can I specify those parameters -- string[] sources, string[] references, string[] defines, and string outputFile -- of EditorUtility.CompileCSharp()?
Thanks very much for any help.
Answer by whydoidoit · May 13, 2013 at 01:56 PM
Everything I can find seems to point to that being a bad idea - so what I did was store the name of the script and wait for the editor script to be re-initialized after a successful compile and then add it.
The answer here: http://answers.unity3d.com/questions/377425/add-component-button-doesnt-work.html includes a download for my version of that.
Your answer
Follow this Question
Related Questions
The Script Equivilent of dragging a hierarchy of meshes over a preexisting prefab? 0 Answers
Can't open scripts with monodevelop? 1 Answer
AssetPreview.GetMiniTypeThumbnail not working for custom scripts 0 Answers
UniSciTE in version 3.x Script Edtior 1 Answer
Can I auto run a script when editor launches or a project finishes loading? 4 Answers