Search Unity

Is there a way to attach a script in a game object in editor mode before runtime?

Discussion in 'Editor & General Support' started by thyoon7043, Mar 8, 2019.

  1. thyoon7043

    thyoon7043

    Joined:
    Feb 11, 2019
    Posts:
    1
    I'm creating a plug-in that imports a data source into Unity from a web authoring tool like Scratch, and configures it in hierachy same as a web authoring tool.
    All assets must be registered in the hiraraki before runtime.
    I finished the importing the script from the outside into the asset folder.
    However, I can not attach the script on gameObject in hierachy.
    Is there a way to attach a script in a game object in editor mode before runtime?

    Code (CSharp):
    1. string sourceFile = "D:\\Test1.cs";
    2. string destFile = "D:\\Dongguk_plugin\\Assets\\customAsset\\scrip\\Test1.cs";
    3. System.IO.File.Copy(sourceFile, destFile, false);
    4. string assetPath = "Assets/customAsset/scrip/Test1.cs";
    5. AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.Default);
    6. AssetDatabase.SaveAssets();
    7. AssetDatabase.Refresh();
    8. MonoScript script = AssetDatabase.LoadAssetAtPath<MonoScript>(unityPath);
    9. Debug.Log("script -- > " + script);
    10. string[] results = AssetDatabase.FindAssets("Test1");
    11. foreach (string guid in results)
    12. {
    13.         unityPath = AssetDatabase.GUIDToAssetPath(guid);
    14.         Debug.Log("unityPath : " + unityPath);
    15. }
    16. GameObject parentObj = new GameObject("TestParentObj");
    17. // addComponent 1
    18. Type type;
    19. if (script != null)
    20. {
    21.         //this line debugs "AddComponent asking for invalid type" because script.GetClass() returns null
    22.         type = script.GetType();
    23.      
    24.         if (type != null)
    25.         {
    26.                 Debug.Log("1. script type -- > " + type);
    27.                 parentObj.AddComponent(type);
    28.         }
    29.         else
    30.         {
    31.                 Debug.Log("1. script type -- > null");
    32.         }
    33.      
    34. }
    35. // addComponent 2
    36. type = Type.GetType("Test1");
    37. if (type != null)
    38. {
    39.         parentObj.AddComponent(type);
    40. }
    41. else
    42. {
    43.         Debug.Log("2. type -- > null");
    44. }
    45. // addComponent 3
    46. MonoScript monoScript = (MonoScript)FindObjectOfType(typeof(MonoScript));
    47. if (monoScript)
    48.         Debug.Log("MonoScript object found: " + monoScript.name);
    49. else
    50.         Debug.Log("No MonoScript object could be found");