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;
}
}
}
@MattGen
Copy link

MattGen commented Sep 16, 2015

Hello ! I stepped on this on Unity Answers, [edited] Ok, I (mostly) solved my issue thanks to you !
T-H-A-N-K - Y-O-U - ! ! !

Tip : To get it to work with LOD trees, just replace GetComponent on line 28 by GetComponentInChildren And... TaDaaa !

But it doesn't copy rotation, do you know how to fix this ?

treez

[Edit] I have another issue with my own version : It copies every LOD mesh renderers, I'm currently trying to solve this. I have two main ideas : "loading all the mesh renderers, Destoying useless ones" or "Stop searching for mesh renderers once it detects one". I guess the second solution would be better right ?

[Edit] Forked this : https://gist.github.com/MattGen/d315c92a7139778b2e67

ps : Cool now I know what Git Gist is made for, thanks ;)

@MattGen
Copy link

MattGen commented Dec 22, 2015

Hey !
I've updated my forked version, supporting LODs and rotation ;)

@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