ExampleFollowSpline.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 that the spline is an independant mathematical component and can be used for other purposes than mesh deformation.
  8. ///
  9. /// This component is only for demo purpose and is not intended to be used as-is.
  10. ///
  11. /// We only move an object along the spline. Imagine a camera route, a ship patrol...
  12. /// </summary>
  13. [ExecuteInEditMode]
  14. [RequireComponent(typeof(Spline))]
  15. public class ExampleFollowSpline : MonoBehaviour {
  16. private GameObject generated;
  17. private Spline spline;
  18. private float rate = 0;
  19. public GameObject Follower;
  20. public float DurationInSecond;
  21. private void OnEnable() {
  22. rate = 0;
  23. string generatedName = "generated by " + GetType().Name;
  24. var generatedTranform = transform.Find(generatedName);
  25. generated = generatedTranform != null ? generatedTranform.gameObject : Instantiate(Follower, gameObject.transform);
  26. generated.name = generatedName;
  27. spline = GetComponent<Spline>();
  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. void EditorUpdate() {
  38. rate += Time.deltaTime / DurationInSecond;
  39. if (rate > spline.nodes.Count - 1) {
  40. rate -= spline.nodes.Count - 1;
  41. }
  42. PlaceFollower();
  43. }
  44. private void PlaceFollower() {
  45. if (generated != null) {
  46. CurveSample sample = spline.GetSample(rate);
  47. generated.transform.localPosition = sample.location;
  48. generated.transform.localRotation = sample.Rotation;
  49. }
  50. }
  51. }
  52. }