Skip to content

Instantly share code, notes, and snippets.

@MattGen
Forked from rmalecki/PlaceTreeShadowCasters.cs
Last active November 2, 2017 18:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save MattGen/d315c92a7139778b2e67 to your computer and use it in GitHub Desktop.
Save MattGen/d315c92a7139778b2e67 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;
Debug.Log ("tree : " + tree.rotation);
GameObject obj = GameObject.Instantiate(prefab, pos, Quaternion.AngleAxis(tree.rotation * Mathf.Rad2Deg, Vector3.up)) as GameObject;
MeshRenderer renderer = obj.GetComponentInChildren<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.rotation = Quaternion.AngleAxis (tree.rotation * Mathf.Rad2Deg, Vector3.up);
t.parent = parent.transform;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment