- Home /
Add renderer to LOD via script
I'm trying to group my individual objects' LODs together into different segments of a grid to help optimize performance. I'm fairly confident my logic is sound: the grid segments have trigger colliders. When a LOD-able object enters its trigger, it runs this script to (theoretically) add the object's renderers to the grid cell's appropriate LODs:
private void OnTriggerEnter(Collider c)
{
if (c.gameObject.tag == "Detail")
{
LODGroup l = this.gameObject.GetComponent<LODGroup>();
GameObject obj = c.gameObject;
obj.GetComponent<LODGroup>().enabled = false;
for (int i = 0; i < l.GetLODs().Length; i++)
{
if (i < obj.transform.childCount)
{
Renderer[] temp = l.GetLODs()[i].renderers;
l.GetLODs()[i].renderers = new Renderer[l.GetLODs()[i].renderers.Length+1];
for (int j = 0; j < temp.Length; j++)
{
l.GetLODs()[i].renderers[j] = temp[j];
}
l.GetLODs()[i].renderers[l.GetLODs()[i].renderers.Length-1] = obj.transform.GetChild(i).GetComponent<Renderer>();
}
}
}
}
However, nothing actually happens. I went into Debug mode and looked at the grid cells' LOD groups, and all their renderers arrays were empty with length 0. I guess my question boils down to: can a script emulate the nice, clean, simple behavior of the LOD Group "Add" button?
This may help you: https://github.com/purpl3grape/Unity-LOD-Auto-Assign/blob/main/LODAssignment.cs
For this script, it requires that the LOD object is nested anywhere within a Parent Object with the LODGroup component.
1) Add this script anywhere in scene. On empty game object for example.
2) Right click the script menu for context menu options.
3) Select ContextMenu("Assign This Script to all LOD Group Objects")
4) Select ContextMenu("Adding LOD child Objects")