- Home /
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.
Thanks
Answer by fotaras · Jun 14, 2015 at 04:50 PM
The best way of doing that is using the reset
for google: $$anonymous$$onoBehaviour void Reset() is basically Unity's on component added (onadded component) event (hook)
Best solution! Unlike others, this one gets called if you attach a component on a disabled game object.
Reset is not called when you ctrl+D an object, if that's something that you need (like assigning an internal ID). See my answer below if required.
Answer by ConfucianFighter · May 03, 2016 at 06:24 PM
void Reset() is called on a monobehaviour in edit mode when it is first added.
Answer by graham · Apr 13, 2012 at 08:32 AM
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.
I created a class to derive from, based on your suggestion. The only thing I don't like about it is that any derived classes are ALSO subject to [ExecuteInEdit$$anonymous$$ode]. Usage: Override FirstPassFunction() with desired "OnCreation" behavior.
using UnityEngine;
[ExecuteInEdit$$anonymous$$ode]
public class FirstPass$$anonymous$$onoBehaviour : $$anonymous$$onoBehaviour {
[SerializeField][HideInInspector]
private bool firstPassFlag=true;
void Awake()
{
if (firstPassFlag)
{
firstPassFlag = false;
FirstPassFunction();
}
}
protected virtual void FirstPassFunction()
{
}
}
Answer by mirswith · Apr 04, 2012 at 10:42 PM
Take a look at MonoBehaviour and determine which event best fits your needs; Awake() maybe.
Answer by bloodthirst69 · Mar 17 at 01:25 PM
Use the "componentWasAdded" editor callback , here's an example i posted where it's being used