AIDestinationSetter.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. using UnityEngine;
  2. using System.Collections;
  3. namespace Pathfinding {
  4. /// <summary>
  5. /// Sets the destination of an AI to the position of a specified object.
  6. /// This component should be attached to a GameObject together with a movement script such as AIPath, RichAI or AILerp.
  7. /// This component will then make the AI move towards the <see cref="target"/> set on this component.
  8. ///
  9. /// See: <see cref="Pathfinding.IAstarAI.destination"/>
  10. ///
  11. /// [Open online documentation to see images]
  12. /// </summary>
  13. [UniqueComponent(tag = "ai.destination")]
  14. [HelpURL("http://arongranberg.com/astar/documentation/stable/class_pathfinding_1_1_a_i_destination_setter.php")]
  15. public class AIDestinationSetter : VersionedMonoBehaviour {
  16. /// <summary>The object that the AI should move to</summary>
  17. public Transform target;
  18. IAstarAI ai;
  19. void OnEnable () {
  20. ai = GetComponent<IAstarAI>();
  21. // Update the destination right before searching for a path as well.
  22. // This is enough in theory, but this script will also update the destination every
  23. // frame as the destination is used for debugging and may be used for other things by other
  24. // scripts as well. So it makes sense that it is up to date every frame.
  25. if (ai != null) ai.onSearchPath += Update;
  26. }
  27. void OnDisable () {
  28. if (ai != null) ai.onSearchPath -= Update;
  29. }
  30. /// <summary>Updates the AI's destination every frame</summary>
  31. void Update () {
  32. if (target != null && ai != null) ai.destination = target.position;
  33. }
  34. }
  35. }