Skip to content

Instantly share code, notes, and snippets.

@rmalecki
Created September 11, 2015 16:06
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save rmalecki/5fe4092b6b739209061b to your computer and use it in GitHub Desktop.
Save rmalecki/5fe4092b6b739209061b to your computer and use it in GitHub Desktop.
Unity 5: Create stand-in geometry for Terrain trees to bake correct lightmaps
using UnityEngine;
using UnityEngine.Rendering;
using UnityEditor;
public class PlaceTreeShadowCasters
{
[@MenuItem ("Terrain/Place Tree Shadow Casters")]
static void Run()
{
Terrain terrain = Terrain.activeTerrain;
if (terrain == null )
{
return;
}
TerrainData td = terrain.terrainData;
GameObject parent = new GameObject("Tree Shadow Casters");
foreach (TreeInstance tree in td.treeInstances)
{
Vector3 pos = Vector3.Scale(tree.position, td.size) + terrain.transform.position;
TreePrototype treeProt = td.treePrototypes[tree.prototypeIndex];
GameObject prefab = treeProt.prefab;
GameObject obj = GameObject.Instantiate(prefab, pos, Quaternion.AngleAxis(tree.rotation, Vector3.up)) as GameObject;
MeshRenderer renderer = obj.GetComponent<MeshRenderer>();
renderer.receiveShadows = false;
renderer.shadowCastingMode = ShadowCastingMode.On;
GameObjectUtility.SetStaticEditorFlags(obj, StaticEditorFlags.LightmapStatic);
Transform t = obj.transform;
t.localScale = new Vector3(tree.widthScale, tree.heightScale, tree.widthScale);
t.parent = parent.transform;
}
}
}
@avotas
Copy link

avotas commented Jun 4, 2017

Is it possible to expand this script to include instanced trees created under Paint Details? We are using the additional brush set to create more realistic distribution of trees and low-lined plants.

Tress are created with '3D Object -> Tree' normally, saved as a prefab, then are loaded as 'Add Detail Mesh'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment