- Home /
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?
I meant inside the editor. So when you drag and drop your script on top of a game object the code executes.
Answer by meat5000 · Feb 11, 2016 at 03:59 PM
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.
Answer by alankemp · Feb 12, 2016 at 01:34 PM
You can use the Reset function which only gets called in the editor when a script is first attached to an object.
http://docs.unity3d.com/ScriptReference/MonoBehaviour.Reset.html
Answer by felixfors · Feb 11, 2016 at 08:08 PM
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");
}
Your answer

Follow this Question
Related Questions
Please help my head is burning from this problem : i have multiple gameobject , same script 1 Answer
Script on multiple objects not working properly! 1 Answer
Adding script during runtime 2 Answers
How to detect if two objects become a square ? 1 Answer
Object instances in code lifetime in comparison with gameobject 0 Answers