Saturday, October 30, 2010

A Unity Shader LOD Script.

using UnityEngine;
using System.Collections;

public class LOD : MonoBehaviour
{
//distances where LOD transitions occur.
public float[] lodLevels = new float[] { 1000f, 800f, 600f, 400f, 200f, 100f, 50f, 10f };

//These are the builtin LOD values for Unity shaders.
int[] shaderLOD = new int[] { 600, 500, 400, 300, 250, 200, 150, 100 };

void Start ()
{
StartCoroutine ("UpdateLOD");
}

void SetLOD (int LOD)
{
foreach (var i in renderer.sharedMaterials) {
i.shader.maximumLOD = shaderLOD[LOD];
}
}

IEnumerator UpdateLOD ()
{
var period = Random.value;
var cam = Camera.main.transform;
float[] levels = new float[lodLevels.Length];
int i = 0;
foreach (var level in lodLevels) {
levels[i++] = level * level;
}
while (true) {
var distance = (transform.position - cam.position).sqrMagnitude;
var LOD = levels.Length - 1;
foreach (var level in levels) {
if (distance > level) {
SetLOD (LOD);
break;
}
LOD--;
}
// make LOD checking non deterministic. avoids stampeding LOD calls?
yield return new WaitForSeconds (period);
}
}

}

3 comments:

Simon Wittber said...

NB: This is only useful for unique models (Eg boss models) which have their own unique material.

Aubrey said...

If you used .material instead of .sharedMaterial, couldn't you work around the unique requirement?

Robin said...

Can you explain how this script works please? I can't quite figure out shaderlod from the docs alone

Popular Posts