Is there a way to run a script on adding a script to an object?

I want to execute a script when I add a certain script to a gameObject. This is what I would like in code:

class MyScript : Monobehaviour 
{
    void onScriptAttached()
   {
        // Call some other script
        // In my case to generate some code
    }
}

Is there any way to do this?

[edit]

Appearently I have not been clear enough. I don’t want to add this script when playing. I want to drag and drop the script on top of a gameobject in the editor. Then when the script is added I want to run some code. I tried something using a custom editor that seems to be able to do this, but I don’t think this is the way to go.

This would be the script to execute:

public class CodeGenerator : MonoBehaviour
{

    public void SaySomething()
    {
        Debug.Log("Something!");
    }
}

And this is the code that makes it happen (I not taking it into account that I only want to execute this code once yet, because I don’t think this is the proper solution):

[CustomEditor(typeof(CodeGenerator))]
public class CodeGeneratorInspector : Editor
{
    CodeGenerator generator;

    // Use this for initialization
    void OnEnable () {
        generator = (CodeGenerator)target;
        SceneView.onSceneGUIDelegate += GeneratorUpdate;
    }

    void GeneratorUpdate(SceneView sceneview)
    {
        generator.SaySomething();
    }
}

It just feels wrong to abuse the custom editors in this way, kinda hacky. What’s the proper way of achieving this?

Simply place the calls to the other script inside the Start() of the script you add. Itll run automatically then, when the script is added.

You can use the Reset function which only gets called in the editor when a script is first attached to an object.

I havent tried the code but I think that it would look something like this.

gameObject.AddComponent<scriptTest>();
		if(gameObject.GetComponent<scriptTest> !=null)
		{
			Debug.Log("We do have the script");
		}