SetActiveRecursively in Array

Hi all! I’m writing myself a little helper class who’s purpose to to turn off all the objects I drop into an array and them randomly turn one of them back on again (like for a randomized image or something). The issue I’m having is that while (I think) my logic is sound, all of my objects get enabled every time the function fires. Any idea what’s wrong?

public class RandomlyEnableOne : MonoBehaviour
{
	public GameObject[] randomlyEnableOneOfThese;
	
	void OnEnable()
	{
		// Disable all of them
		foreach(GameObject go in randomlyEnableOneOfThese)
		{
			go.SetActiveRecursively(false);
		}
		
		randomlyEnableOneOfThese[Random.Range(0, randomlyEnableOneOfThese.Length)].SetActiveRecursively(true);
	}
}

1 Answer

1

Maybe the problem isn’t “all get enabled” but maybe “none get disabled.” Print the size of the array? Maybe this code runs before it gets filled (or not at all?) Try putting the same code in a function that runs when you press Z.

Most likely not the problem, but SetActiveRecursively is being phased out. SetActive() now does the same thing, faster, without annoying warnings.

I've commented out line 13 and it disables all of them, which is why I find this so perplexing. As far as SetActive() goes, I'm still working off of 3.5.7 as we don't quite have the budget at the moment to upgrade all our licenses to pro 4.0. Thanks for your answer!