Search Unity

Receiving a null reference exception after attempting to cast from GameObject

Discussion in 'Scripting' started by TheLurkingDev, Jan 12, 2014.

  1. TheLurkingDev

    TheLurkingDev

    Joined:
    Nov 16, 2009
    Posts:
    91
    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?

    Code (csharp):
    1.  
    2. string pathToTerrainTexture = "Terrain/" + GameData.SelectedTerrainTexture;
    3.                 Texture terrainTexture = Resources.Load(pathToTerrainTexture) as Texture;
    4.                 GameObject[] terrains = GameObject.FindGameObjectsWithTag("Terrain");
    5.                 foreach(GameObject terrain in terrains)
    6.                 {
    7.                     Debug.Log("GameObject: " + terrain.name.ToString());
    8.                     Terrain thisTerrain = terrain.gameObject.GetComponent<Terrain>();   // Cast from GameObject to terrain.
    9.                     Debug.Log("Terrain name: " + thisTerrain.name.ToString());   // Null reference exception.
    10.                     thisTerrain.renderer.material.SetTexture("_MainTex", terrainTexture);   // Null reference exception.
    11.                 }
    12.  
     
  2. Zeblote

    Zeblote

    Joined:
    Feb 8, 2013
    Posts:
    1,102
    Code (csharp):
    1. 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?

    Code (csharp):
    1. Debug.Log("GameObject: " + terrain.name.ToString());
    Also, why are you calling ToString() on a string?
     
  3. unitylover

    unitylover

    Joined:
    Jul 6, 2013
    Posts:
    346
    You may have to type cast the getcomponent call, I.e typing "as Terrain" on the end.
     
  4. LightStriker

    LightStriker

    Joined:
    Aug 3, 2013
    Posts:
    2,717
    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.
     
  5. Zeblote

    Zeblote

    Joined:
    Feb 8, 2013
    Posts:
    1,102
    Nahh the problem is that he's using terrain.gameObject. GameObject.gameObject does not exist.
     
  6. LightStriker

    LightStriker

    Joined:
    Aug 3, 2013
    Posts:
    2,717
    How is that even compiling?
     
  7. Zeblote

    Zeblote

    Joined:
    Feb 8, 2013
    Posts:
    1,102
    That's a good question actually. I have no idea.