Toggle all child objects at once?

I have empty game object that’s the parent of a bunch of child objects. Is there something I could put in the empty parent so that I can toggle the mesh renderers of all of the child object at once?

Add this to the parent object script:

    void ToggleRenderersInChildren()
    {
        foreach (MeshRenderer renderer in GetComponentsInChildren<MeshRenderer>())
        {
            renderer.enabled = !renderer.enabled;
        }
    }

When I tried it, I got this error…
Assets/ParentMeshRenderer.cs(1,6): error CS0116: A namespace can only contain types and namespace declarations
Sorry if it’s really simple, but I’m not great with CSharp.

Sounds like you should put the function inside your class.
You can google the error code (CS0116 in this case) and find a example of what’s wrong.

Post the code from ParentMeshRenderer.cs here please.

Okay, but it’s the same as yours…

void ToggleRenderersInChildren()
{
    foreach (MeshRenderer renderer in GetComponentsInChildren<MeshRenderer>())
    {
        renderer.enabled = !renderer.enabled;
    }
}

And that’s all?:slight_smile: Don’t you have any class declaration?

Okay, when I said I don’t know MUCH about CSharp, I meant to say, I know absolutely nothing. I use pretty much all Javascript. Anyways, I rewrote it. I thought I got it right, but I got a parsing error on line (12,9). Here’s what I wrote

using UnityEngine;
using System.Collections;

public class ParentMeshRenderer : MonoBehaviour {

    void ToggleRenderersInChildren()
    {
        foreach (MeshRenderer renderer in GetComponentsInChildren<MeshRenderer>())
        {
            renderer.enabled = !renderer.enabled;
        }
    }

Well, there’s missing closing bracket in the class declaration.

Oh, okay, I should have noticed that before. I didn’t get any errors, but the script doesn’t do anything. I can’t even toggle it.2173677--143901--Screenshot (179).png

it’s not going to “do anything” until you call the function, i.e. use it. In order to do that you’ll need to make the ToggleRenderersInChildren() function public so you can call it from a button or from another script, or add in Start(), Update(), OnTrigger…() function etc.

I tested that code (with the closing bracket) set as a public function and hooked up to a canvas button works fine.