MatrixProvider.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace Knife.HologramEffect
  5. {
  6. [ExecuteAlways]
  7. public class MatrixProvider : MonoBehaviour
  8. {
  9. [SerializeField] private string propertyName = "_CustomMatrix";
  10. [SerializeField] private Renderer[] targetRenderers;
  11. [SerializeField] private bool eliminateRootBoneMatrix;
  12. private MaterialPropertyBlock materialPropertyBlock;
  13. private void OnEnable()
  14. {
  15. if (this == null)
  16. return;
  17. if (materialPropertyBlock == null)
  18. materialPropertyBlock = new MaterialPropertyBlock();
  19. if (targetRenderers != null)
  20. {
  21. foreach (var r in targetRenderers)
  22. {
  23. if (r != null)
  24. {
  25. Matrix4x4 matrix = transform.localToWorldMatrix;
  26. if(eliminateRootBoneMatrix)
  27. {
  28. SkinnedMeshRenderer skinnedMeshRenderer = r as SkinnedMeshRenderer;
  29. if(skinnedMeshRenderer != null)
  30. {
  31. Transform rootBone = skinnedMeshRenderer.rootBone;
  32. if(rootBone != null)
  33. {
  34. matrix = rootBone.localToWorldMatrix * matrix;
  35. }
  36. }
  37. }
  38. r.GetPropertyBlock(materialPropertyBlock);
  39. materialPropertyBlock.SetMatrix(propertyName, matrix);
  40. r.SetPropertyBlock(materialPropertyBlock);
  41. }
  42. }
  43. }
  44. }
  45. private void OnValidate()
  46. {
  47. OnEnable();
  48. }
  49. }
  50. }