- Home /
The question is answered, right answer was accepted
Is it possible to catch a can't add script error in the editor?
So here's the setup.
I have an abstract class named Alpha that inherits from Monobehaviour. I have classes Beta, Charlie, Delta, etc, that inherit from class Alpha, but are not abstract. Upon trying to attach script Alpha to a game object, unity throws the exception "Can't add script" since it's abstract. I know this is intentional.
My question is: when a user tries to add the script 'Alpha' to a game object, is it possible to catch the "Can't add script" error and notify the user to select one of the scripts that inherit Alpha?
EDIT: Don't know if it helps, but I am using Unity 2018.1.2f1
Answer by Bunny83 · Feb 21, 2019 at 06:22 PM
No, your can't. And it would be absurd to catch it. You usually have countless of scripts / source files which may contain classes that do not even represent a component. All such scripts can not be added to a gameobject and would trigger that same error from the editor. You should better think about a proper script organisation in your folder structure. Your base class Alpha doesn't even need to be in a script with the same name. It could be in any script. The name matching requirement only applies to classes that are actually attached to gameobjects.
You can hide classes from the Add Component menu by marking them with
[AddComponentMenu("")]
This essentially removes the script from the menu. I have never tried making the base class "internal" instead of "public". It may work as well. Though depending on the usage of the abstract base class it might not be an option to make it internal.
Of course the user can still drag the script manually to a gameobject, but as i said, that's true for any script that doesn't contain a monobehaviour. So just make sure you organise your files properly. If you have a more complex system it's common to use some sort of "core" subfolder which contains files that need to be there but the user never directly interacts with. Aside that folder you can create a folder "components" (or whatever fits your system) which only contains scripts which can be added as component.
Yeah, I figured as much. I just wanted to see if there was a way eli$$anonymous$$ate all confusion on what script to add to the object. I suppose it'll still be pretty hard to get confused if the folders are organized in a pleasant fashion.
Thanks.
Follow this Question
Related Questions
AddComponent not working 3 Answers
Adding a component in the editor with a script 0 Answers
GO.AddComponent just adds an empty Script 1 Answer
5.0.0b9 Addcomponent cause a crash 1 Answer
Compilation error, Unity 5 0 Answers