MegaModLODManager.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using UnityEngine;
  2. using System.Collections;
  3. [System.Serializable]
  4. public class MegaModLOD
  5. {
  6. public Mesh mesh;
  7. public float distance;
  8. }
  9. public class MegaModLODManager : MonoBehaviour
  10. {
  11. public GameObject theCamera;
  12. public GameObject meshContainer;
  13. public MegaModLOD[] levelsOfDetail;
  14. public int currentLOD = -1;
  15. private float lastLODCheckTime = 0;
  16. // Change this value to specify how many seconds elapsed to check LOD change
  17. private float LODCheckInterval = 0.2f;
  18. void Update()
  19. {
  20. // Not need to check every frame
  21. if ( (Time.time - lastLODCheckTime) > LODCheckInterval )
  22. {
  23. float distanceToCamera = Vector3.Distance(transform.position, theCamera.transform.position);
  24. int selectedLOD = levelsOfDetail.Length - 1;
  25. for ( int i = levelsOfDetail.Length - 1; i >= 0; i-- )
  26. {
  27. if ( distanceToCamera > levelsOfDetail[i].distance )
  28. {
  29. selectedLOD = i;
  30. break;
  31. }
  32. }
  33. if ( selectedLOD != currentLOD )
  34. {
  35. currentLOD = selectedLOD;
  36. MegaModifyObject modifyObject;
  37. modifyObject = meshContainer.GetComponent<MegaModifyObject>();
  38. if ( modifyObject != null )
  39. {
  40. // Change meshFilter to use new mesh
  41. meshContainer.GetComponent<MeshFilter>().mesh = levelsOfDetail[selectedLOD].mesh;
  42. modifyObject.MeshUpdated();
  43. // Update modifiers stack state depending on its MaxLOD specified in Unity Editor
  44. for ( int i = 0; i < modifyObject.mods.Length; i++ )
  45. {
  46. MegaModifier m = modifyObject.mods[i];
  47. m.ModEnabled = (m.MaxLOD >= currentLOD);
  48. }
  49. }
  50. }
  51. lastLODCheckTime = Time.time;
  52. }
  53. }
  54. }