Receiving a null reference exception after attempting to cast from GameObject

As you can see below, I am trying to cast from a GameObject to custom type, which is in this case a prefab called “Terrain”. The first call to Debug.Log is properly outputting the GameObject ‘name’ property, which is a dynamically instantiated clone of the Terrain prefab. After I attempt to cast the GameObject to the Terrain type and perform any operations on it I am receiving a null reference exception. What am I doing wrong?

string pathToTerrainTexture = "Terrain/" + GameData.SelectedTerrainTexture;
				Texture terrainTexture = Resources.Load(pathToTerrainTexture) as Texture;
				GameObject[] terrains = GameObject.FindGameObjectsWithTag("Terrain");
				foreach(GameObject terrain in terrains)
				{
					Debug.Log("GameObject: " + terrain.name.ToString());
					Terrain thisTerrain = terrain.gameObject.GetComponent<Terrain>();   // Cast from GameObject to terrain.
					Debug.Log("Terrain name: " + thisTerrain.name.ToString());   // Null reference exception.
					thisTerrain.renderer.material.SetTexture("_MainTex", terrainTexture);   // Null reference exception.
				}
terrain.gameObject.GetComponent<Terrain>();

terrain is already the GameObject. No need to put .gameObject there. You’re probably getting confused because of misleading variable names?

Debug.Log("GameObject: " + terrain.name.ToString());

Also, why are you calling ToString() on a string?

You may have to type cast the getcomponent call, I.e typing “as Terrain” on the end.

No, the generic method returns the proper type.

I would guess he get a null Terrain because one of his GameObject in his array doesn’t have the component.
What’s weird is, he should have the name of that specific GameObject because he is logging it the line just over.

Nahh the problem is that he’s using terrain.gameObject. GameObject.gameObject does not exist.

How is that even compiling?

That’s a good question actually. I have no idea.