Last active
November 27, 2021 12:34
-
-
Save nothke/c6566368f5cbbec47859 to your computer and use it in GitHub Desktop.
[Unity] A simple and fast LOD system
This file contains hidden or 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
// Update: not needed for Unity 5 since LOD groups are available in personal edition | |
//======================================== | |
//== Simple LOD system == | |
//== File: LOD.cs == | |
//== By: Ivan Notaros - Nothke == | |
//== Use and alter Freely == | |
//======================================== | |
//Description: | |
// Switches models according to distance from player | |
using UnityEngine; | |
using System.Collections; | |
public class LOD : MonoBehaviour | |
{ | |
[System.Serializable] | |
public class LODLevel | |
{ | |
public GameObject LODobject; | |
public float LODin = 0; | |
public float LODout = 100; | |
[HideInInspector] | |
public bool prevAppear; | |
} | |
public LODLevel[] LODlevels; | |
public float LODmultiplier = 1; // multiplies LODin and LODout in all LODobjects, this is a quick way to make it configurable in game graphics settings | |
public float checkRate = 1; // how often is the distance checked, in seconds | |
public bool debug; | |
Transform player; | |
float distance; | |
IEnumerator Start() | |
{ | |
player = Utils.GetPlayer().transform; // Change this to whatever way you get the player position | |
foreach (LODLevel ll in LODlevels) | |
{ | |
ll.LODobject.renderer.enabled = false; | |
} | |
yield return new WaitForSeconds(Random.value); | |
do | |
{ | |
DoLOD(); | |
yield return new WaitForSeconds(checkRate); | |
} while (true); | |
} | |
void DoLOD() | |
{ | |
distance = Vector3.Distance(transform.position, player.position); | |
foreach (LODLevel ll in LODlevels) | |
{ | |
if (distance >= ll.LODin * LODmultiplier && distance < ll.LODout * LODmultiplier) | |
{ | |
if (!ll.prevAppear) | |
{ | |
ll.LODobject.renderer.enabled = true; | |
ll.prevAppear = true; | |
if (debug) Debug.Log("LOD - " + ll.LODobject + " appears"); | |
} | |
} | |
else | |
{ | |
if (ll.prevAppear) | |
{ | |
ll.LODobject.renderer.enabled = false; | |
ll.prevAppear = false; | |
if (debug) Debug.Log("LOD - " + ll.LODobject + " hidden"); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment