Changing opacity of a child object

Hey guys.
I’m trying to change the opacity of a child object.
Here is my function for it:

void SetOpacity(GameObject obj, int alpha)
	{
		Transform mesh = obj.transform.FindChild("Mesh");

		Color meshColor = mesh.renderer.materials[0].color;
		meshColor.a = alpha;
	
		mesh.renderer.materials[0].color = meshColor;	
		
	}

But all I get is an error saying:

MissingComponentException: There is no 'Renderer' attached to the
game object, but a script is trying to access it.

The gameobject definitely has a child called “Mesh” and it has a renderer.
Any ideas what I should do?
Thanks.

Sounds tricky. Hard to pin down to any specific problems, but here are some things you might check:

Is obj the right object? Is FindChild() finding the right child? It seems like a stupid question, but you can never be too sure.

Does obj have any other children named “Mesh” which might be getting in the way?

Does “Mesh” have a mesh renderer attached directly, or is it in yet another child? Some asset importers give you a mesh renderer in a child object.

You might check if it matters whether obj, “Mesh”, or the renderer attached to “Mesh” is currently enabled/active. I’ve noticed that some of Unity’s lookup calls are reluctant to find disabled objects.

You could try using GetComponentInChildren().

If all else fails, you might try recreating the problem in an empty scene with only the required objects/components/scripts present. Might help expose something unique about the situation in which your script is getting that error.