How to add Custom Script Created from Editor Window to a GameObject

Hi I have created a custom editor Window to create scripts and automatically organize them in different folders. Now i am facing an issue where if i want to attach the same script that will be created when i click the “Create Button” to a GameObject in Hierarchy. Can anyone point me in the direction of a solution.

Attaching Editor Window Screenshot as well.

I’m assuming you mean you’re making a new script asset, ergo a monoscript asset. You can get the System.Type of the monobehaviour or scriptable object definition in the script with the following method: Unity - Scripting API: MonoScript.GetClass

So you would just need to hold onto a reference to the created monoscript asset (or its path), wait until after a domain reload using the appropriate callbacks, and then get the Type defined by your script - presumably a MonoBehaviour component in this example - and then use that type to add it to your game object.

Also props for using editor tooling to expedite the creation of scripts. If it helps, there’s an undocumented class called UnityEditor.ProjectWindowUtil that has a few methods that can create script assets using templates, so you can get auto-generated namespaces from your assembly definitions, files names, etc.

If you haven’t used script templates, you can read about them here: https://support.unity.com/hc/en-us/articles/210223733-How-to-customize-Unity-script-templates

Thank you very much for the information. I will definitely Give it a try and Let you know how it goes.

1 Like

Thank you Very much @spiney199 It worked like a charm.

1 Like