How to disable MeshRenderer for multiple components?

I built my own player ship model in Unity, not the prettiest but I like it! This means that the Mesh Renderer components are on each of the individual 3d objects I built it from, rather than there being only one Mesh Renderer for the whole prefab. Thankfully I added a single Box Collider so that is working as intended in the lesson.

How would I disable the Mesh Renderer for all the components of my Prefab?

Or if that’s the wrong approach, how would I go about combining the renderers so there is only one for the whole model? I assume I’d need an actual texture for the whole ship model for this rather than using the Mesh Renderer to give the components colours, so I hope the first approach is workable.

I also tried using Destroy(gameObject) but that just made the ship disappear without restarting the level, presumably because the gameObject with the script attached had been destroyed before the command to restart the level was executed.

2 Likes

Hi! Welcome back.

There are actually a lot of ways to do this, the simplest one would be to go through each of the mesh renderers and deactivate them one by one, this is done with a loop, the code would look similar to this:

    foreach (Transform child in transform)
    {
        MeshRenderer renderer = child.GetComponent<MeshRenderer>();

        if (renderer != null)
        {
            renderer.enabled = false;
        }
    }

That code will not deactivate any MeshRenderer in the parent object, keep that in mind. This is also quite inefficient, you would want to create a list and populate in the Awake method so you don’t have to call GetComponent during a taxing time. That would look similar to this:

    List<MeshRenderer> renderers = new List<MeshRenderer>();

    // Start is called before the first frame update
    void Awake()
    {
        foreach (Transform child in transform)
        {
            MeshRenderer renderer = child.GetComponent<MeshRenderer>();

            if (renderer != null)
            {
                renderers.Add(renderer);
            }
        }
    }

    void DeactivateRenderers()
    {
        foreach (var renderer in renderers)
        {
            renderer.enabled = false;
        }
    }

If you don’t want to make a list and deal with it in code you could simply make an array and populate it in the inspector.

    [SerializeField] MeshRenderer[] renderers = null;

    void DeactivateRenderers()
    {
        foreach (var renderer in renderers)
        {
            renderer.enabled = false;
        }
    }

There are other methods, but this is by far the simplest. You could also merge all the meshes in code so you end up using a single renderer, but that’s way more complicated.

5 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms