- Home /
How to replace the Button component in the editor with a subclassed version
I am trying to replace a component UnityEngine.UI.Button with my own sub classed component CustomButton (which derives from UnityEngine.UI.Button).
This is all working but one thing that is annoying and I want to fix is that in order to replace an existing component UnityEngine.UI.Button with my new one CustomButton in the editor I have to delete the UnityEngine.UI.Button component before adding the CustomButton. This is annoying as I lose all the properties set in the UnityEngine.UI.Button component which apply to the CustomButton, so I have to input the values in again.
If I just try to add CustomButton while a UnityEngine.UI.Button is already attached I get an error box from the editor:
Can't add script Can't add 'CustomButton' to ButtonName because a 'Button' is already added to the game object! A GameObject can only contain one 'Selectable' component
What I would like to do is intercept this error store the values of UnityEngine.UI.Button, then remove the component, add my new CustomButton component and set it's values.
First can I intercept this error message, or the action of adding a new component before anything is added? How would I go about doing this?
I've not had experience with creating editor scripts yet, but I am a competent coder who uses C#.
Thanks in advance for any help
Answer by ModLunar · Jul 21, 2019 at 12:26 AM
Sorry this is very late! At the top-right of your Inspector, there are 3 little bars. Click them, and you can change to Debug Mode Inspector. This will draw even most private variables, ignoring custom PropertyDrawers, and fun fact: It will even expose their real names if you hold "Alt" on the keyboard.
Once you're in Debug Mode Inspector, scroll down to the Button Component, and you'll be able to change the "Script" there. Beware that you won't be able to find the Button component again through here. The only way to change it back with this, would be to Ctrl + Z/Undo. But you should be able to find your component just fine here.
You can get back to the default Inspector (out of Debug Mode) by clicking the "Normal" option in the first screenshot above.
I hope this helps! You can use this to switch scripts anywhere, pretty much!
This works amazingly, thank you! Should definitely be marked as the correct answer.