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.