SkyCloudMask.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. #if UNITY_EDITOR
  4. using UnityEditor;
  5. #endif
  6. using UnityEngine;
  7. namespace Kamgam.SkyClouds
  8. {
  9. [ExecuteAlways]
  10. public class SkyCloudMask : MonoBehaviour
  11. {
  12. [SerializeField]
  13. protected int _maskIndex = 1;
  14. protected string _maskShaderPropertyName = "_Mask1";
  15. public int MaskIndex
  16. {
  17. get => _maskIndex;
  18. set
  19. {
  20. if (value != _maskIndex)
  21. {
  22. _maskIndex = value;
  23. _maskShaderPropertyName = "_Mask" + _maskIndex;
  24. }
  25. }
  26. }
  27. public List<Material> SkyCouldMaterials = new List<Material>();
  28. public float Padding = 0.2f;
  29. public void Update()
  30. {
  31. var pos = transform.position;
  32. var radius = transform.localScale.x * 0.5f + Padding;
  33. setMask(pos, radius);
  34. }
  35. private void setMask(Vector3 pos, float radius)
  36. {
  37. if (SkyCouldMaterials != null)
  38. {
  39. foreach (var material in SkyCouldMaterials)
  40. {
  41. if (material == null)
  42. continue;
  43. var sphereMask = new Vector4(
  44. pos.x,
  45. pos.y,
  46. pos.z,
  47. radius
  48. );
  49. material.SetVector(_maskShaderPropertyName, sphereMask);
  50. }
  51. }
  52. }
  53. public void OnDisable()
  54. {
  55. setMask(new Vector3(0, -999, 0), 0.001f);
  56. }
  57. #if UNITY_EDITOR
  58. public void Reset()
  59. {
  60. SkyCouldMaterials.Clear();
  61. string[] materialGUIDs = AssetDatabase.FindAssets("t:Material");
  62. foreach (string guid in materialGUIDs)
  63. {
  64. string path = AssetDatabase.GUIDToAssetPath(guid);
  65. Material material = AssetDatabase.LoadAssetAtPath<Material>(path);
  66. if (material.shader.name != "SkyClouds")
  67. continue;
  68. if (material != null && material.name.StartsWith("SkyClouds"))
  69. {
  70. SkyCouldMaterials.Add(material);
  71. }
  72. }
  73. EditorUtility.SetDirty(this);
  74. }
  75. public void OnValidate()
  76. {
  77. _maskShaderPropertyName = "_Mask" + _maskIndex;
  78. }
  79. #endif
  80. }
  81. }