Check if Script exists in Project (not already assigned to a GameObject in the Scene)

We have an editor script, let's call it ScriptA, which does these steps:

1) Auto-generates a new script, let's call it ScriptB, and place ScriptB into the Asset\Resources folder. This works as expected.

2) Call AssetDatabase.Refresh(); so the script shows up inside the project. This works as expected.

3) Adds ScriptB as a component to a GameObject.

Here lies the issue.

In step 3, we get an error message saying the file doesn't exist. We can see the file in the explorer and in the Unity3D's project resource folder. We can also drag and drop the newly created ScriptB onto the GameObject in the scene manually. So we know the new script is correctly formed. We can also open the new script in Visual Studios for editing.

So we thought to some type of UI locking loop (remembering this is an editor) as a step 2.5 which would keep checking if the script exists to the Unity Engine yet. Once true, the continue to step 3.

It would appear that the UnityEngine/Editor has to detect a new file in the resource folder, then import it we are guessing. And as ScriptA is moving so fast, this does not occur before we try to add ScriptB as a component to the gameObject.

Does anyone know what this command is? We tried Resource.Load and Resource.LoadAtPath but the asset is a script and not one of the others shown in the examples on the web.

BTW, if anyone is wondering what our editor does? We are working on making a Form Designer (aka graphical GUI designer).

Thanks in advanced for any help,

Scott Peal Global Chief Architect Company Automation LLC

        GameObject newFormGameObject = new GameObject(NewFormName);
        newFormGameObject.transform.parent = FormsRoot.transform;
        newFormGameObject.tag = "guiForm";

        string FormScriptsDirectory = "Assets/Resources";
        string path = Path.Combine(FormScriptsDirectory, "TestScript.cs");
        string FormCode =   "using UnityEngine;" + Environment.NewLine +
                            "using System.Collections;" + Environment.NewLine +
                            "public class TestScript : MonoBehaviour" +
                            Environment.NewLine +
                            "{" +
                            "}";

        using (StreamWriter sw = File.CreateText(path))
        {
            sw.Write(FormCode);
        }

        AssetDatabase.ImportAsset("TestScript.cs");
        newFormGameObject.AddComponent("TestScript.cs");

Try using AssetDatabase.ImportAsset(path); followed by AddComponent