SFX_TargetAttacher.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using UnityEngine;
  3. // ReSharper disable once CheckNamespace
  4. namespace QFX.SFX
  5. {
  6. [Serializable]
  7. public class SFX_TargetAttacher
  8. {
  9. private Transform _transform;
  10. public Transform Target { get; private set; }
  11. private bool _isAttached;
  12. public void Attach(Transform anchor, Transform selfTransform)
  13. {
  14. _transform = selfTransform;
  15. Target = anchor;
  16. _isAttached = true;
  17. }
  18. public void FindAndAttach(string anchorName, Transform parent, Transform selfTransform)
  19. {
  20. var anchor = FindChildByRecursion(parent, anchorName);
  21. if (anchor == null)
  22. {
  23. Debug.LogWarning("Anchor not found");
  24. return;
  25. }
  26. Target = anchor;
  27. _transform = selfTransform;
  28. _isAttached = true;
  29. }
  30. public void DeAttach()
  31. {
  32. _isAttached = false;
  33. _transform = null;
  34. }
  35. public void Update()
  36. {
  37. if (!_isAttached)
  38. return;
  39. _transform.position = Target.position;
  40. _transform.rotation = Target.rotation;
  41. }
  42. private static Transform FindChildByRecursion(Transform aParent, string aName)
  43. {
  44. if (aParent == null)
  45. return null;
  46. var result = aParent.Find(aName);
  47. if (result != null)
  48. return result;
  49. foreach (Transform child in aParent)
  50. {
  51. result = FindChildByRecursion(child, aName);
  52. if (result != null)
  53. return result;
  54. }
  55. return null;
  56. }
  57. }
  58. }