Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

NullRefernceException

Discussion in 'Scripting' started by RPGFabi, Nov 27, 2019.

  1. RPGFabi

    RPGFabi

    Joined:
    Oct 24, 2019
    Posts:
    29
    Code (CSharp):
    1.  
    2. int TerrainOffset_X = Width * SingleTerrainSize;
    3.                         int TerrainOffset_Z = Height * SingleTerrainSize;
    4.                        
    5.                         // Terraincreation
    6.                             Terrain NewTerrain = new Terrain();
    7.                        
    8.                         // TerrainInfo
    9.                             NewTerrain.transform.position = new Vector3(TerrainOffset_X, 0, TerrainOffset_Z);
    10.                             NewTerrain.transform.rotation = Quaternion.identity;
    11.  
    12.                        
    13.  // Terraindata
    14.                             TerrainData NewData = new TerrainData();
    15.                             NewData.heightmapResolution = SingleTerrainHMSize;
    16.                             NewData.size = new Vector3(SingleTerrainSize, TerrainMaxHeight, SingleTerrainSize);
    17.                             NewData.baseMapResolution = 1024;
    18.  
    19.                        
    20. // Add Data to Terrain
    21.                             NewTerrain.terrainData = NewData;
    22.  
    Now my Question:

    Why leads
    NewTerrain.transform.position = new Vector3(TerrainOffset_X, 0, TerrainOffset_Z)
    to a NullReferenceException??

    All Variables have a value and it should (?!) work.
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,748
    You can't "new" anything that's a Behaviour; that class doesn't work that way. You have to create a GameObject, then attach a Terrain component to it using AddComponent<Terrain>.
     
    Joe-Censored likes this.
  3. RPGFabi

    RPGFabi

    Joined:
    Oct 24, 2019
    Posts:
    29
    Wait. So I don't need to add a new Terrain, i need to add a new Gameobject and asign a Terrain to it?