Execute Code When Component Added

I have a script that generates a simple mesh in a function called Rebuild(). Normally this function is called whenever Radius changes in the GUI. However, it doesn’t get called when I first add the script/component to the a game object. What’s the best way of doing this? I basically want to execute code on a component when it’s added to a game object.


The best way of doing that is using the reset

void Reset() is called on a monobehaviour in edit mode when it is first added.

Use the “componentWasAdded” editor callback , here’s an example i posted where it’s being used

I believe You can use OnValidate function for this. As this can solve your both purpose because it gets called when script loaded and also when you make any changes to the variables of the monobehavior.

Note: This is Editor-only function.

Thanks for the help mirswith, but I couldn’t find what I needed directly. In the end, I used the ExecuteInEditMode attribute on my MonoBehaviour, and combined that with a flag that I check on Update. If the flag is set, I do what I need. Not the most optimal solution, but it seems to work and is simple.

Take a look at MonoBehaviour and determine which event best fits your needs; Awake() maybe.