-
-
Save derricksimpson/0b6a598482ebfa19d1736dbb79bf8d10 to your computer and use it in GitHub Desktop.
Unity 5: Create stand-in geometry for Terrain trees to bake correct lightmaps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEngine.Rendering; | |
using UnityEditor; | |
/* | |
Finds tree instances within terrain data and create's real GameObjects within the scene. (used to bake shadows). | |
Steps: | |
Turn of "Draw Trees" from Terrain config. | |
Select the Terrain | |
Run the editor script. | |
Make sure "Auto Generate" is DISABLED | |
Toggle Off or Delete "Tree Shadow Casters" | |
Re-Enable "Draw Trees" | |
*/ | |
public class PlaceTreeShadowCasters | |
{ | |
[@MenuItem ("Terrain/Place Tree Shadow Casters")] | |
static void Run() | |
{ | |
Terrain terrain = Terrain.activeTerrain; | |
if (terrain == null ) | |
{ | |
// TODO: Throw up a message asking the user to select a terrain | |
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