- Home /
In need of an OnWillDisable() event
So have situation where i my camera is the child of an object that might be disabled. So, when that object is disabled, I attempt to reparent the camera to the next appropriate parent/camera-holder.
However, when editing the transfrom heirarchy during OnDisable, you get this error:
Cannot change GameObject hierarchy while activating or deactivating the parent.
which is problematic.
I do want this to specifically occur when the parent gameObject has its activeSelf set to false, and that doesn't necessarily coincide with any other objects getting their activeSelf set to true, so I can't very well move this to OnEnable on another object.
I also can't just choose to wait a frame before the heirarchy change, because that would require the camera to deactivate for at least 1 frame. Part of the motivation for this system is keeping a camera alive when moving between scenes and positions.
It would be perfect to have an OnPreDisable()
event, but alas. That doesn't seem to be available. I would need to know every place in my code that the parent might be disabled, and run OnPreDisable()
then, which is unideal, and also makes it so i can't test this with the active-checkbox in the editor.
this is a similar problem to this post: https://answers.unity.com/questions/505088/unity4-change-hirachy-ondisable.html but the solutions offered here do not apply well to my situation.
Answer by Vega4Life · Dec 05, 2018 at 07:22 PM
I would just create a simple extension method. Something like this:
public static class ExtensionMethods
{
public static void PreDisableCameraChange(this GameObject go, Transform newParent)
{
Camera.main.transform.SetParent(newParent);
go.SetActive(false);
}
}
Then instead of doing gameObject.SetActive(false); - you do this instead:
gameObject.PreDisableCameraChange(newParentTransform);
Answer by surfuay · Dec 05, 2018 at 07:51 PM
what If you had 2 cameras and both responded to the disable function of the first parent.
if parent 1 is enabled camera1.setactive(true) and camera2.setactive(false)
and then if parent 1 is disabled do the inverse. I would put camer2 under parent 2 and you'll just have some script communication to write out.
Your answer
![](https://koobas.hobune.stream/wayback/20220612183418im_/https://answers.unity.com/themes/thub/images/avi.jpg)