I need to handle OnDisable event for my MonoBehaviour script component. While object with this component is instantiated on the scene, everything works fine, but when I manually disable the component on the master prefab (in the project window) — OnDisable is not being called.
Could this be a bug, or it’s by design?
Answer by AlwaysSunny
Apr 12, 2015 at 06:42 AM
Making changes to the "enabled" status of prefab elements and components in the project view does not invoke events on scripts, nor does it make changes to instances of those prefabs already in the scene. The ability to make those changes to the prefab is just giving you a way to control its initial state when it's instantiated.
Thank you for the answer!
It’s kinda sad though… It means I have to check for enable\disable events myself in the editor script? Like constantly polling in Update function every selected object that have my script and wait if it would be removed or disabled… That would be really ugly :(
I'm not sure I understand why you think you'd benefit from OnDisable callbacks for an uninstantiated prefab. From a logical perspective, it doesn't make sense for an uninstantiated prefab to "do" anything.
Haven't scripted for the editor in a while, but I seem to recall it's easy enough to grab every object of a type (your class) and make a change to the group. This could be based on checking the enabled status of your uninstantiated prefab.
Well, I’m making a plugin that is changing objects material, and so I need to revert the material to its original state, when the user removes my component from the prefab.
Anyway, thank you for help. I was able to make some kind of a hack, when in editor I’m constantly checking if the component was removed and handle all the needed work there. Not very nice solution, but seems to work fine.
Answer by hyp3rbolic
The answer is for an older Unity version. Currently in Unity Version 5.6 the following code:
enabled = false;
Fires the OnDisable method and it is, working.
Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.
The best place to ask and answer questions about development with Unity.
To help users navigate the site we have posted a site navigation guide.
If you are a new user to Unity Answers, check out our FAQ for more information.
Make sure to check out our Knowledge Base for commonly asked Unity questions.
If you are a moderator, see our Moderator Guidelines page.
We are making improvements to UA, see the list of changes.
Answers and Comments
4 People are following this question.
onGui not getting called every frame?
Attached scripts as List?
unity script error
C# Inheriting from MonoBehaviour but still be able to instantiate with new()? How should I do this?
How do I use a game object to store a singleton?