NullReferenceException on GetComponent().enabled

I want to active/deactive meshrenderer of the child under a gameobject, so here is what I did:

I created a gameobject, and created a child called “Name” under it.
Then I attach the code under that gameobject and try to get the meshrenderer under the “Name”

Then I got this after the running…

NullReferenceException: Object reference not set to an instance of an object
Test.Start () (at Assets/Scripts/Test.cs:17)

Here is the code:

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour{

	// Use this for initialization
	void Start () {
		Transform displayName = transform.FindChild("Name");
		
		if (displayName = null){
			return;
		}
		
		displayName.GetComponent<MeshRenderer>().enabled = true;
		
	}

Any ideas?

You’re setting the displayName to null in line 10, instead of checking for null. Should be:

if (displayName == null){ // note the double ==

It should be

 MeshRenderer mr = displayName.gameObject.GetComponent<MeshRenderer>();
 if (mr != null)
    mr.enabled = true;

this will provide error checking on all parts. The game object is where the MeshRenderer is located (if there is one);