Hi,
I have a strange issue with subclass of button.
When I drop a prefab (which contains a subclass of button) on my scene in editor mode, start of my custom class is called… That’s not what I expect.
Is it a normal behaviour for a button to call Start when adding the gameobject to the scene in editor mode?
Is it a good practice to inherit from Button ?
I would appreciate if you could help me !
Thanks in advance !
Really for all types of game objects, the Start or Awake function will be called just like you’re seeing. You might be thinking that the start function is meant to do whatever happens when the user clicks the button…? That is not the case though. Start is called when a script is first enabled, and then it’s done. Awake, is similar, yet different… it gets called right when the game object is initialized… before Start function.
These functions are typically used to set things up for your object, such as some parameters.
What you might want to do is go check out the various UI tutorials here to understand how to make the button work, as there are at least a couple different methods you can use for that (creating your own events, or mapping a custom function to the button press)…
Thanks for your answer but that’s not my question.
I aggree, my explanation may not be really clear…
I know how to use Start and Awake.
I don’t understand why ,but when I put a prefab in the scene that contains a button in edit mode, the function “Start” of my component that inherit from Button is called, although it’s not runtime.
Well cstooch, you should probably read the whole post,
“When I drop a prefab (which contains a subclass of button) on my scene in editor mode, start of my custom class is called… That’s not what I expect.”
Start shouldn’t be called when dropping a prefab in EDITOR mode, the only way i could see Start called in editor is a
[ExecuteInEditMode] attribute at the top of your class, since you are inheriting from Button class, it might be the button class that have the ExecuteInEditMode, causing it to trigger your child Start()
Button derives from UISelectible, which has an [ExecuteInEditMode] attribute. In your start use the Unity_Editor directive and skip if its not in playmode.