AlpakaJoe
AlpakaJoe

Reputation: 593

Add Trees to Terrain C# with TreeInstance

I try to add trees to my terrain with the following code:

// Create Trees
for (int x = 0; x < terrainData.heightmapWidth; x++)
{
    for (int z = 0; z < terrainData.heightmapWidth; z++)
    {
        if (GetBiome(x, z) == "Grasland")
        {
            int r = UnityEngine.Random.Range(0, 500);
            if (r == 0)
            {
                Terrain terrain = GetComponent<Terrain>();
                TreeInstance treeTemp = new TreeInstance();
                treeTemp.position = new Vector3(x, 0, z);
                treeTemp.prototypeIndex = 0;
                treeTemp.widthScale = 1f;
                treeTemp.heightScale = 1f;
                treeTemp.color = Color.white;
                treeTemp.lightmapColor = Color.white;
                terrain.AddTreeInstance(treeTemp);
                terrain.Flush();
            }
        }
    }
}

the function GetBiome() works correctly, i checked that by placing the trees as GameObjects and it worked fine.

Is there something missing that i didn't thought of?

Because there's not a single tree generated.

The tree i want to generate is set up under PaintTrees:

enter image description here

Upvotes: 2

Views: 2978

Answers (2)

FlayerDev
FlayerDev

Reputation: 13

A bit late but, instead of

int r = UnityEngine.Random.Range(0, 500);
        if (r == 0)

do

int r = UnityEngine.Random.Range(0, 500);
        if (r >= 0 && <= 1) 

to check for range. Because you're checking for a impossible number it will always come close but never 0 for example 0.000230...f you will need to Math floor it or check for range like I did

Upvotes: 0

aaronedmistone
aaronedmistone

Reputation: 999

Please read my notes as comments below, I hope this explains and resolves the issue. I have tested this in unity to confirm.

// Create Trees

//make these float otherwise your position math below is truncated
for (float x = 0; x < terrainData.heightmapWidth; x++)
{
    //heightmapHeight not heightmapWidth
    for (float z = 0; z < terrainData.heightmapHeight; z++)
    {
        Terrain terrain = GetComponent<Terrain>();
        int r = UnityEngine.Random.Range(0, 500);
        if (r == 0)
        {
            TreeInstance treeTemp = new TreeInstance

            //position is local and expects value between 0 and 1
            treeTemp.position = new Vector3(x / terrainData.heightmapWidth, 0, z / terrainData.heightmapHeight),

            treeTemp.prototypeIndex = 0;
            treeTemp.widthScale = 1f;
            treeTemp.heightScale = 1f;
            treeTemp.color = Color.white;
            treeTemp.lightmapColor = Color.white;
            terrain.AddTreeInstance(treeTemp);
            terrain.Flush();
        }
    }
}

Upvotes: 1

Related Questions