SetActive and SetActiveRecursively

Im having problems setting my child gameobjects active in unity 4.

For example I have a GameObject called TimeTrialPanel with some child game objects nested

so when I use the old way, TimeTrialPanel.SetActiveRecursively(true) it sets TimeTrialPanel and all its children active which is what I want but i know its a depreciated method.

When i use TimeTrialPanel.SetActive(true); it just sets TimeTrialPanel and not its children active. This seems wrong as the docs say it should affect the children

any advice please

1 Like

SetActive(true) does set children active, unless they were inactive in the scene to start with. Assuming the object and children are active to start with, then SetActive(false) will set the object and children to inactive, and SetActive(true) will set them all to active. Objects retain their original active state, so if a child is inactive originally, then SetActive won’t have any effect on it.

–Eric

1 Like

Ah so if i want an object and its children to be unactive at the start of the scene (say a pause menu) I have to set it and its children active in editor, then set SetActive(false) on the parent at game start, then SetActive(true) when pause is pressed?

This has been resolved. The problem was with NGUI and not Unity, setactive doesn’t work on NGUI panels correctly. I fixed it by using the supplied NGUITools.SetActive() method, hope that helps anyone else who might have encountered this problem

I had a similar issue, where some of my code depended on the old behavior of SetActiveRecursively. I was able to mimic the behavior of that function pretty easily:

In my old code, I had a subset of the heirarchy that would only be turned on at certain times. It had a function that looked like this:

public void SetChildrenActive (bool active) {
		for (int i=0; i<transform.childCount; i++) {
			transform.GetChild(i).gameObject.SetActiveRecursively (active);
		}
	}

After upgrading to Unity 4 and while dealing with my usage SetActiveRecursively, I ended up replacing the snippet above with this:

	public void SetChildrenActive (bool active) {
		SetChildrenActive (gameObject, active);
	}

	private void SetChildrenActive (GameObject obj, bool active) {
		// Look at all of the children of the object passed in
		for (int i=0; i < obj.transform.childCount; i++) {
			// Get the child object to modify
			GameObject childObj = obj.transform.GetChild(i).gameObject;
			// Set that object's active state.
			childObj.SetActive (active);
			// Call this function on that object to set its children.
			SetChildrenActive (childObj, active);
		}
	}

Works just like before with no nasty warnings. :smile: