I'm trying to make an editor window to ease my workflow of creating enemies. Most parts work fine apart from creating a class and adding it.
void SaveAndCreate()
{
string guid = AssetDatabase.CreateFolder("Assets/Scripts/Enemies/EnemyTypes", enemyData.EnemyName);
string newFolderPath = AssetDatabase.GUIDToAssetPath(guid);
TextAsset templateTextFile = AssetDatabase.LoadAssetAtPath("Assets/CharacterTemplate.txt", typeof(TextAsset)) as TextAsset;
string contents = "";
if (templateTextFile != null)
{
contents = templateTextFile.text;
contents = contents.Replace("CUSTOMCLASS_", enemyData.EnemyName.Replace(" ", ""));
}
using (StreamWriter sw = new StreamWriter(string.Format(newFolderPath + "/{0}.cs", new object[] { enemyData.EnemyName.Replace(" ", "") })))
{
sw.Write(contents);
}
objToCreate = new GameObject(enemyData.EnemyName);
objToCreate.name = enemyData.EnemyName;
needToAttach = true
}
Through this im creating the folders and class that i need which uses inheritance from a Monobehaviour. The objects name is the class, so if im making a "Dog" enemy the class that gets generated is "Dog.cs" which inherits from "Animals.cs". Now my issue lies with actually adding that class.
//_go.AddComponent(Type.GetType(enemyData.EnemyName + ".cs"));//
String ScriptName = objToCreate.name;
Type MyScriptType = Type.GetType(ScriptName + "UnityEngine ,Assembly-CSharp");
objToCreate.AddComponent(MyScriptType);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
needToAttach = false;
As you can see i have tried a few things but since adding components through string is obsolete i cannot! I get this error "AddComponent asking for invalid type". So my question is is there any way for this to happen? I generate the dog.cs through script, create the prefab and assign to it through its name. This way i want to create enemies easy and adding all the necessary components automatically and not having to create each class on my own and assign in the editor. Thank you!
I should note that if i create another GUI button that assigns it , it works. But i do want it to work with the same button. In current setup the function to add the new component is in Update with this code. needToAttach is a bool to check when it needs and i updated the above to include it!
if (EditorApplication.isCompiling) { return; }
if (needToAttach)
{
// AddClass();
}