问题
- 我想通过Terrain绘制工具给树木添加季节性变化。但树在Hierarchy面板不并不是以GameObject的形式存在。
原因
没有换树木Prefab的功能。
解决方案
Unity Terrain用数组Terrain.treeInstances暴露树的实例。数组的每一个树的实例在Terrain设置(prototypeIndex)中都有一个属性存储树prefab的配置。
树prefab 通过改变这个值自动更新。
TreeInstance[] currentTreeList;
TerrainData terrain;
int springTreeIndex;
int fallTreeIndex;
bool season;
void ChangeSeasons ()
{
// The currentTreeList array must be at least
terrain.treeInstances.Length in size
//currentTreeList数组的大小至少为terrain.treeInstance.Length
System.Array.Copy (terrain.treeInstances, currentTreeList, terrain.treeInstances.Length);
if (terrain.treeInstances.Length == currentTreeList.Length)
{
for (int tcnt=0; tcnt < currentTreeList.Length; tcnt++)
{
if (season)
{
if (currentTreeList [tcnt].prototypeIndex == springTreeIndex)
currentTreeList [tcnt].prototypeIndex = fallTreeIndex;
}
else
{
if (currentTreeList [tcnt].prototypeIndex == fallTreeIndex)
currentTreeList [tcnt].prototypeIndex = springTreeIndex;
}
}
terrain.treeInstances = currentTreeList;
season = !season;
}
}
更多信息
http://answers.unity3d.com/questions/521056/access-terrain-tree-material-from-script.html