- Home /
After SetActive(false/true) scripts no longer update?
Hi, because of an issue I couldn't find a better answer for, I need to call this code each frame:
gameObject.SetActive(false);
gameObject.SetActive(true);
The problem is, script on children don't work afterward. Even though every game object has activeInHierarchy and activeSelf == true, and every script on these objects reports enabled == true, the Update functions on these scripts are not being called. Any script on the gameObject I'm changing (or its parents) works, but scripts on children stop working, yet say they're enabled.
Simplified version of what I'm doing:
//Example Object
//ParentObject (w/ ParentScript.cs)
// > ChildObject (w/ ChildScript.cs)
//ChildScript.cs
void Update() {
Debug.Log("Child");
}
//ParentScript.cs
void Update() {
Debug.Log("Parent");
//with these 2 lines, "Child" is never printed, without it is.
gameObject.SetActive(false);
gameObject.SetActive(true);
}
I thought I understood all this active/enabled stuff, but I guess not yet.
Edit: Actually I have a hunch about this, but can anyone link to a reference about when objects are actually activated/deactivated? What if deactivating turns off the parent before the child scripts run, but only activates again after the next game loop starts - that would definitely cause it?
No that should all work - and I'd be very surprised if it's generally broken because my stuff all seems to work and it wouldn't if that were broken for me... Are you sure something else isn't disabling them? Coroutines will have stopped running if you did that BTW
The simple example worked for me too, only after exiting and restarting Unity though... ghosts, probably.
$$anonymous$$y main game code is still doing it, its a more complex GameObject and I'm making the SetActive calls at the end of my Update function, in a script attached to the top-level parent GameObject.
Basically my setup is like this (2d game):
Parent (has script doing the SetActive calls)
->Head (Quad with image)
->Arm1
--->Quad (w/ arm texture)
->Arm2
--->Quad (w/ arm texture)
--->Gun (Quad w/ texture and a GunScript)
->Leg1
->Leg2 (both Legs are Quad w/ Texture and LegScript so they move when walking)
I don't do anything in Coroutines except occasionally waiting for one-off sounds to destroy, and like I said I'm calling SetActive, twice in a row, right at the end of Update.
I guess I found a 'solution' of sorts, except at this point I'm hacking a hack and it just feels like something is very wrong...
To fix my issue of "toggling active on a parent messes up children" I just do individual toggles on all the deepest descendants (actually just the two that I need the hack for), because toggling active in a script doesn't mess up itself or its siblings.
Yeah it's a terrible answer. Please please help me find a better one!