How to execute a method when I create a new script, or I saved an existing one ? (and get his type)

I want to know how to execute a method when I create a new script, or rename an existing one ?

I know Unity do some processes when scripts are created. For example, when you create a script, the script is added to the list of components in the window Component > Scripts > NamespaceOfYourScript > NameOfYOurScript. I want to do something like that, but for my own custom window. I’m pretty sure that the process is accessible, but I don’t know its name and how to access and use it.

I have already searched on the documentation, unity answers, stack overflow, but I don’t find yet what I was looking for (without to know what is the exact process keyword you are looking for, it’s not easy to search).

I want to get a script a bit like this kind :

using UnityEngine;
using UnityEditor;

public class MyScript : SomeScriptProcess ()
{
    void OnScriptSaved (System.Type TheScriptThatWasJustSaved)
    {
        //I execute my stuff here
    }
}

Any helps would be great. :slight_smile:

Something like this is possible, but not the way you try to approach it. First of all, unity does not now if a script is saved/created recently, at least they aren’t telling. They just recompile the whole assemblies.

But you could write an editor script that when triggered collects all the MonoBehaviour classes found inside the project assembly. Something like this:

[UnityEditor.Callbacks.DidReloadScripts]
private static void OnScriptsReloaded()
{
	Debug.Log("OnScriptsReloaded");

	foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
	{
		if (a.GetName().Name != "Assembly-CSharp") continue;

		foreach (Type t in a.GetTypes())
		{
			if (typeof(MonoBehaviour).IsAssignableFrom(t))
			{
				// do something with the script
				//
			}
		}
	}
}

This method will find all your scripts as Type. You then can store that inside a list and check it next time for any added/removed scripts by checking the difference. That list can then be used to display in a List to select a type for example.

Hope that helps.

@Nischo : I tried. It works very well. Good job. Thanks a lot ! :slight_smile: