Search Unity

How to generate set number of cubes randomly on a plane?

Discussion in 'World Building' started by coder_58, Aug 29, 2022.

  1. coder_58

    coder_58

    Joined:
    Mar 29, 2020
    Posts:
    31
    Hi,

    As the title says, I'm a bit confused as to how I can generate a set number of cubes (say, 100) on a plane, in a way that some are stacked on top of each other (in piles, essentially), and others simply lay on the plane. I don't want to generate the blocks as the player moves (like in Minecraft) but rather, create the 100 blocks and arrange them on the plane in a random way as described above. Thanks!

    (If you're wondering, I tagged this question as 'documentation' since there's no other tag available)
     
  2. CyplexGaming

    CyplexGaming

    Joined:
    Aug 24, 2019
    Posts:
    4
    first make a prefab of the cube you wanna spawn and reference it in ur script:
    public GameObject cubePrefab;


    now we loop through however many cubes your wanna spawn with a for loop, generating 2 floats randomly between the edges of your plane each time and putting a cube there (this asssumes your plane is at the origin and is scaled on the x and z by 10):
    for (int i = 0; i < 100; i++){
    float x = Random.Range(-10f, 10f);
    float z = Random.Range(-10f, 10f);
    Instantiate(cubePrefab, new Vector3(x, 1, z), Quaternion.identity);
    }


    the stacking is a little more complicated. first, make x and z declared at the top of ur script, declare a new
    float increment = 0
    at the top, and declare y as 1 at the top as well. then i'd just use a random.range(0, 1) every time you run the for loop, and set the y level on the instantiation to one above whatever it usually is if the random is 1, and normal if its 0:

    for (int i = 0; i < 100; i++){
    if (Random.Range(0, 1) == 1){
    Instantiate(cubePrefab, new Vector3(x, y + increment, z), Quaternion.identity);
    i++;
    increment++;
    } else {
    increment = 0;
    x = Random.Range(-10f, 10f);
    z = Random.Range(-10f, 10f);
    Instantiate(cubePrefab, new Vector3(x, y, z), Quaternion.identity);
    }}


    pls reply if it breaks i wont have a chance to test if it works sry

    (btw put this code in the start function)