Skip to main content
1 of 2
stratos la
  • 61
  • 1
  • 11

Adding custom made class through name and not component

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;
    }

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();   

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!

stratos la
  • 61
  • 1
  • 11