Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- public class DistanceLOD : MonoBehaviour
- {
- [SerializeField] private float updateDelay = 0.1f;
- [SerializeField] private float cullDistance = 10f;
- [SerializeField] private Renderer[] renderers;
- [SerializeField] private Vector3 center = Vector3.zero;
- [SerializeField] private Vector3 size = Vector3.one;
- private float distance;
- private Bounds bounds;
- private Camera mainCamera;
- private void Awake()
- {
- mainCamera = Camera.main;
- }
- private void OnEnable()
- {
- InvokeRepeating("OnUpdate", 0f, updateDelay);
- }
- private void OnDisable()
- {
- CancelInvoke("OnUpdate");
- }
- private void OnUpdate()
- {
- UpdateDistance();
- EnableRenderers(cullDistance > distance);
- }
- private void EnableRenderers(bool enable)
- {
- if (renderers == null)
- {
- return;
- }
- for (var i = 0; i < renderers.Length; ++i)
- {
- if (renderers[i] == null)
- {
- continue;
- }
- renderers[i].enabled = enable;
- }
- }
- private void UpdateDistance()
- {
- if (mainCamera == null)
- {
- return;
- }
- var camPosition = mainCamera.transform.position;
- if (bounds.Contains(camPosition))
- {
- distance = 0f;
- }
- else
- {
- var closestPoint = bounds.ClosestPoint(camPosition);
- distance = (closestPoint - camPosition).magnitude;
- }
- }
- private void UpdateBounds()
- {
- bounds = new Bounds(transform.TransformPoint(center), size);
- }
- private void OnDrawGizmos()
- {
- if (mainCamera == null)
- {
- mainCamera = Camera.main;
- }
- UpdateBounds();
- UpdateDistance();
- Gizmos.color = Color.cyan;
- Gizmos.DrawWireCube(bounds.center, bounds.size);
- if (mainCamera != null)
- {
- var camPosition = mainCamera.transform.position;
- var closestPoint = bounds.ClosestPoint(camPosition);
- Gizmos.DrawLine(camPosition, closestPoint);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement