Search Unity

Create terrain from script

Discussion in 'Scripting' started by ohm, Apr 25, 2009.

  1. ohm

    ohm

    Joined:
    Aug 24, 2008
    Posts:
    88
    Hi,

    I wonder if anyone have been able to create a terrain from script? I've tried lots of different approaches and read all the posts on the forum but either unity crashes silently or it complains about the terrain not being connected properly.

    Some examples:

    This results in "Terrain not correctly connected to a terrainData object".
    Code (csharp):
    1.  
    2. GameObject g = new GameObject();
    3. Terrain t = (Terrain)g.AddComponent("Terrain");
    4.  
    This crashes the editor.
    Code (csharp):
    1.  
    2. TerrainData d = new TerrainData();
    3. GameObject g = Terrain.CreateTerrainGameObject(d);
    4.  
    This results in "Exception: X or Y base out of bounds. Setting up to 513x513 while map size is 0x0"
    Code (csharp):
    1.  
    2. TerrainData d = new TerrainData();
    3. float[,] height_data = new float[513, 513];
    4. d.SetHeights(0, 0, height_data);
    5. GameObject g = Terrain.CreateTerrainGameObject(d);
    6.  
    This crashes the editor.

    Code (csharp):
    1.  
    2. TerrainData d = new TerrainData();
    3. d.Init(1024, 1024, 512);
    4. d.size = new Vector3(1000, 10, 1000);
    5. float[,] height_data = new float[513, 513];
    6. d.SetHeights(0, 0, height_data);
    7. GameObject g = Terrain.CreateTerrainGameObject(d);
    8.  

    Cheers,
    //Fredrik
     
  2. ohm

    ohm

    Joined:
    Aug 24, 2008
    Posts:
    88
    Anyone?


    //Fredrik
     
  3. rom

    rom

    Joined:
    Jul 2, 2006
    Posts:
    265
    As far as i know the TerrainData needs to be stored as an asset
    Create your terrain in the normal way, so that the TerrainData.asset appears in you project view.
    You can then delete it from you scene if you like, and then use Terrain.CreateTerrainGameObject referencing the TerrainData asset
     
  4. ohm

    ohm

    Joined:
    Aug 24, 2008
    Posts:
    88
    Worked gloriously! Thanks!


    //Fredrik