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?