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.
}