Generating Buildings at Runtime – Simple

To see this in action head open the example scene BuildR2\Genesis\Genesis Runtime Example.unity in your Unity project.

The following code takes a Genesis Plot defined in the editor (selectedPlot) and generates a building inside it at a specified interval (generationTime) using a defined set of building constraints (constraint).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
    using UnityEngine;
    using BuildR2;
    using BuildR2.Genesis;

    public class SimpleRuntimeExample : MonoBehaviour
    {
        public BuildingRuntime building;
        public BuildingContraints constraint;
        public GenesisPlot selectedPlot;
        public float startTime = 1.0f;
        public float generationTime = 10.0f;
        private GenesisSettings _settings;

        private void Start()
        {
            _settings = GenesisSettings.Get();
            InvokeRepeating("Generate", startTime, generationTime);
        }

        private void Generate()
        {
            if(building!=null) building.Clear();

            GRandom.GenerateNewSeed();
            _settings.seed = GRandom.seedInt;
            selectedPlot.density = GRandom.Range(10, 20);
            building = BuildingGenerator.CreateRuntime(selectedPlot, constraint, _settings.defaultGeneratedBuildingName);
        }
    }

The Generate() function is called at the specified interval and is the method used to generate a new building from scratch.

1
building.Clear()

Remove all the currently used renderers that have been allocated

1
2
GRandom.GenerateNewSeed();
_settings.seed = GRandom.seedInt;

Create a new random seed and assign it to the global setting seed.

1
selectedPlot.density = GRandom.Range(10, 20);

Modifying the plot density will change the height of a generated building. Here it will be randomly chosen between 10 and 20.

1
building = BuildingGenerator.CreateRuntime(selectedPlot, constraint, settings.defaultGeneratedBuildingName);

Finally the BuildingGenerator creation method is called. The plot, constraints are passed and it will output the generated building.

Comments are closed.