Search Unity

Creating a fixed size Terrain with randomly generated objects and layout

Discussion in 'World Building' started by Kuntujin, Aug 14, 2019.

  1. Kuntujin

    Kuntujin

    Joined:
    Aug 14, 2019
    Posts:
    1
    Hi all,

    Very new to Unity and game development in general.

    I've set up an isometric environment with players and enemies.

    What would be the best method for creating a fixed sized terrain (player/user will choose the size that they want) with randomly generated objects and layout.
    For example, a number of buildings of different types in random places, roads and floor textures of different types.
    The terrain will always be flat.

    I've searched the web but everything seems to come back with randomly generated infinite terrains.

    Any advice welcome and appreciated.
    Thanks

    edit:
    I have just found the script below on a website, I guess it would be a good place to start but I'm unsure where I should actually run it from. Should I attach the script to a Terrain GameObject?

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. public class RandomObjects : MonoBehaviour
    4. {
    5. public Terrain terrain;
    6. public int numberOfObjects; // number of objects to place
    7. private int currentObjects; // number of placed objects
    8. public GameObject objectToPlace; // GameObject to place
    9. private int terrainWidth; // terrain size (x)
    10. private int terrainLength; // terrain size (z)
    11. private int terrainPosX; // terrain position x
    12. private int terrainPosZ; // terrain position z
    13. void Start()
    14. {
    15. // terrain size x
    16. terrainWidth = (int)terrain.terrainData.size.x;
    17. // terrain size z
    18. terrainLength = (int)terrain.terrainData.size.z;
    19. // terrain x position
    20. terrainPosX = (int)terrain.transform.position.x;
    21. // terrain z position
    22. terrainPosZ = (int)terrain.transform.position.z;
    23. }
    24. // Update is called once per frame
    25. void Update()
    26. {
    27. // generate objects
    28. if(currentObjects <= numberOfObjects)
    29. {
    30. // generate random x position
    31. int posx = Random.Range(terrainPosX, terrainPosX + terrainWidth);
    32. // generate random z position
    33. int posz = Random.Range(terrainPosZ, terrainPosZ + terrainLength);
    34. // get the terrain height at the random position
    35. float posy = Terrain.activeTerrain.SampleHeight(new Vector3(posx, 0, posz));
    36. // create new gameObject on random position
    37. GameObject newObject = (GameObject)Instantiate(objectToPlace, new Vector3(posx, posy, posz), Quaternion.identity);
    38. currentObjects += 1;
    39. }
    40. if(currentObjects == numberOfObjects)
    41. {
    42. Debug.Log("Generate objects complete!");
    43. }
    44. }
    45. }