131. Finding Game Objects By Name

Hi the following code is throwing a null exception. There is no space in naming the Quad. The name is exactly what the code is trying to find.

        MeshRenderer mesh = transform.Find("Top").GetComponent<MeshRenderer>();
        mesh.material.color = color;

But when I change to this code, its working. How is the above code working for Ben?

    private void SetTopColor(Color color)
    {
        // MeshRenderer mesh = transform.Find("Top").GetComponent<MeshRenderer>();
        // mesh.material.color = color;
        Transform[] childTransforms = GetComponentsInChildren<Transform>();

        foreach(Transform childTransform in childTransforms)
        {
            MeshRenderer mesh = childTransform.GetComponent<MeshRenderer>(); ;

            if (childTransform.name.Equals("Top") && mesh.material.color!=color)
            {
                mesh.material.color = color;
            }
        }
    }

Hi Abhilash,

That’s a good question. To which game object/Transform object is transform in your first example referring to?

In your second example, your code looks for the name of a child of child objects.

transform refers to the empty gameobject which is the parent of the Grid waypoints

Hi, I got why Bens code didnt work for me. I had created script at parent level.

I’m glad you figured the solution out yourself. :slight_smile:

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

Privacy & Terms