从treeinstance[] treeInstances 里删除树 然后
设置terraindata.treeinstances=treeInstances 更新terraindata
再刷新地图数据 terrain.Flush();
即可
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
public Terrain terrain;
public GameObject treePrefab;
// Start is called before the first frame update
TreeInstance[] treeInstances = new TreeInstance[1];//terraindata里树的实例数组数据。
List<TreeInstance> treeInstances2 = new List<TreeInstance>();
int treecount = 10;
void Start()
{
TerrainData terrainData = terrain.terrainData;
terrainData.heightmapResolution = 17; //将地图变小。不然树太小了看不见。。。
TreePrototype treePrototype = new TreePrototype();
treePrototype.prefab = treePrefab;
treePrototype.bendFactor = 1;
terrainData.treePrototypes = new TreePrototype[1] { treePrototype }; //设置树的预制数组
//树的数量,图中数量大于10是因为运行了多次,树未删除。
for (int i=0;i<treecount;i++)
{
TreeInstance treeInstance = new TreeInstance();
treeInstance.widthScale = 1f;
treeInstance.heightScale = 1f;
treeInstance.color = Color.white;
treeInstance.lightmapColor = Color.white;
treeInstance.position = new Vector3(Random.Range(0f, 1f), 0, Random.Range(0f, 1f)); //位置为0-1.0f
treeInstance.prototypeIndex =0;
treeInstances2.Add(treeInstance);
}
treeInstances = treeInstances2.ToArray();
terrainData.SetTreeInstances(treeInstances, true);
terrain.Flush();
}
// Update is called once per frame
void Update()
{
}
public void removeatree()
{
treeInstances2.RemoveAt(0);
treeInstances = treeInstances2.ToArray();
terrain.terrainData.treeInstances = treeInstances;
terrain.Flush();
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?