LuxURP_BillboardBounds.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Serialization;
  5. namespace LuxURPEssentials
  6. {
  7. [RequireComponent(typeof(MeshFilter))]
  8. public class LuxURP_BillboardBounds : MonoBehaviour
  9. {
  10. // using order to fix header/button issue
  11. [Space(5)]
  12. [LuxURP_HelpBtn("h.9i03ddhmnooa")]
  13. [Space(18)]
  14. [SerializeField]
  15. [Tooltip("Scale of the tweaked bounding box.")]
  16. private Vector3 _Scale = new Vector3(1,1,1);
  17. [SerializeField]
  18. [Tooltip("If checked Unity will instantiate the assigned mesh on Start().")]
  19. private bool _createUniqueMesh = false;
  20. [Space(8)]
  21. [SerializeField]
  22. [Tooltip("Check this to preview the scaled bounding box.")]
  23. private bool _drawBounds = true;
  24. private Mesh _Mesh;
  25. void Start()
  26. {
  27. if(_createUniqueMesh)
  28. {
  29. SetBounds();
  30. }
  31. }
  32. void SetBounds() {
  33. if(_Mesh == null)
  34. {
  35. if(!_createUniqueMesh)
  36. {
  37. _Mesh = GetComponent<MeshFilter>().sharedMesh;
  38. }
  39. else
  40. {
  41. // Instatiate assigned mesh
  42. _Mesh = GetComponent<MeshFilter>().mesh;
  43. }
  44. }
  45. if(_Mesh != null)
  46. {
  47. _Mesh.RecalculateBounds();
  48. var bounds = _Mesh.bounds;
  49. var size = bounds.size;
  50. size.x = _Scale.x;
  51. size.y = _Scale.y;
  52. size.z = _Scale.z;
  53. bounds.center = new Vector3(bounds.center.x, bounds.center.y, bounds.center.z);
  54. _Mesh.bounds = new Bounds(bounds.center, size);
  55. if(!_createUniqueMesh)
  56. {
  57. GetComponent<MeshFilter>().sharedMesh = _Mesh;
  58. }
  59. else
  60. {
  61. GetComponent<MeshFilter>().mesh = _Mesh;
  62. }
  63. }
  64. }
  65. void OnDrawGizmosSelected()
  66. {
  67. if(_drawBounds) {
  68. if(_Mesh == null)
  69. {
  70. _Mesh = GetComponent<MeshFilter>().sharedMesh;
  71. }
  72. // Set matrix
  73. Gizmos.matrix = transform.localToWorldMatrix;
  74. // Draw Bounding Box
  75. Gizmos.color = Color.red;
  76. var bounds = _Mesh.bounds;
  77. var size = bounds.size;
  78. // In playmode bounds should be set properly alrady.
  79. if(!Application.isPlaying)
  80. {
  81. size.x = _Scale.x;
  82. size.y = _Scale.y;
  83. size.z = _Scale.z;
  84. bounds.center = new Vector3(bounds.center.x, bounds.center.y, bounds.center.z);
  85. }
  86. Gizmos.DrawWireCube(bounds.center, size);
  87. // Reset matrix
  88. Gizmos.matrix = Matrix4x4.identity;
  89. }
  90. }
  91. }
  92. }