ExampleContortAlong.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEditor;
  4. using UnityEngine;
  5. namespace SplineMesh {
  6. /// <summary>
  7. /// Example of component to show the deformation of a mesh in a changing
  8. /// interval in spline space.
  9. ///
  10. /// This component is only for demo purpose and is not intended to be used as-is.
  11. /// </summary>
  12. [ExecuteInEditMode]
  13. [RequireComponent(typeof(Spline))]
  14. public class ExampleContortAlong : MonoBehaviour {
  15. private Spline spline;
  16. private float rate = 0;
  17. private MeshBender meshBender;
  18. [HideInInspector]
  19. public GameObject generated;
  20. public Mesh mesh;
  21. public Material material;
  22. public Vector3 rotation;
  23. public Vector3 scale;
  24. public float DurationInSecond;
  25. private void OnEnable() {
  26. rate = 0;
  27. Init();
  28. #if UNITY_EDITOR
  29. EditorApplication.update += EditorUpdate;
  30. #endif
  31. }
  32. void OnDisable() {
  33. #if UNITY_EDITOR
  34. EditorApplication.update -= EditorUpdate;
  35. #endif
  36. }
  37. private void OnValidate() {
  38. Init();
  39. }
  40. void EditorUpdate() {
  41. rate += Time.deltaTime / DurationInSecond;
  42. if (rate > 1) {
  43. rate --;
  44. }
  45. Contort();
  46. }
  47. private void Contort() {
  48. if (generated != null) {
  49. meshBender.SetInterval(spline, spline.Length * rate);
  50. meshBender.ComputeIfNeeded();
  51. }
  52. }
  53. private void Init() {
  54. string generatedName = "generated by " + GetType().Name;
  55. var generatedTranform = transform.Find(generatedName);
  56. generated = generatedTranform != null ? generatedTranform.gameObject : UOUtility.Create(generatedName, gameObject,
  57. typeof(MeshFilter),
  58. typeof(MeshRenderer),
  59. typeof(MeshBender));
  60. generated.GetComponent<MeshRenderer>().material = material;
  61. meshBender = generated.GetComponent<MeshBender>();
  62. spline = GetComponent<Spline>();
  63. meshBender.Source = SourceMesh.Build(mesh)
  64. .Rotate(Quaternion.Euler(rotation))
  65. .Scale(scale);
  66. meshBender.Mode = MeshBender.FillingMode.Once;
  67. meshBender.SetInterval(spline, 0);
  68. }
  69. }
  70. }