How to randomly disable/enable children objects in parent object?

Hi,

I would like to be able to randomly turn off renderers in any of the children on a parent object,
e.g. if I press the minus key less and less child objects are shown, if I press plus key then they come back gradually the more I press the plus key. I want to do this to help with game performance so players can adjust the level of details…have no idea how to code this…yet… and would appreciate your input.

Here is what I have tried:

 if(Input.GetKeyDown(KeyCode.Minus))
      var obj1 : GameObject =  GameObject.Find("myparentobj");
      var allChildren = obj1.GetComponentsInChildren(Transform);
        for (i=0;i<allChildren.Length ;i++) {
          try {  
   	   if(allChildren*==(Random.Range(0, allChildren.childCount)))*

_ var child : Transform in allChildren3*;_
_
child.gameObject.GetComponent(MeshRenderer).enabled = false;}_
_
catch (err) { }_
_
}*_
Can someone help me out with this?

Okay so a few things first:

  • When posting here, be precise in what you ask. Here we don’t even know what’s not working (everything according to the code you posted).
  • Get to code in C#, it’s less permissive, and will help you in the end.
  • At least try to post a valid code, without 10 syntax errors.

Now your solution:

for (var i=0;i<allChildren.Length ;i++) {
   try {  
       var rdm = Random.Range(0, allChildren.Length);
       for (var child : Transform in allChildren*) {*

child.gameObject.GetComponent(MeshRenderer).enabled = false;
}
}
catch (err) {}

Random.Range will generate a new number each time it is called. Move the Random.Range outside of the for loop, and store the result into an int. You can also do a check to see if the selected random object is already active, if it is, keep generating new random number until you have an inactive object selected. To avoid an infinite loop, you can store the inactive objects in a list and randomly select one of them from that new list. Also omitting curly braces {} makes the code harder to follow, I’d suggest you define your scopes always.