我尝试使用以下代码将树木添加到地形中:

// 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();
            }
        }
    }
}


函数GetBiome()正常工作,我通过将树放置为GameObjects进行检查,并且工作正常。

是否有我没想到的遗漏?

因为没有生成任何一棵树。

我要生成的树是在PaintTrees下设置的:

c# - 使用TreeInstance将树添加到Terrain C#-LMLPHP

最佳答案

请阅读我的注释作为下面的注释,希望这能解释并解决该问题。
我已经对此进行了统一测试以确认。

// 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();
        }
    }
}

关于c# - 使用TreeInstance将树添加到Terrain C#,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53880451/

10-13 06:45