ClickToMove.cs 677 B

12345678910111213141516171819202122232425
  1. using UnityEngine;
  2. using UnityEngine.AI;
  3. // Use physics raycast hit from mouse click to set agent destination
  4. [RequireComponent(typeof(NavMeshAgent))]
  5. public class ClickToMove : MonoBehaviour
  6. {
  7. NavMeshAgent m_Agent;
  8. RaycastHit m_HitInfo = new RaycastHit();
  9. void Start()
  10. {
  11. m_Agent = GetComponent<NavMeshAgent>();
  12. }
  13. void Update()
  14. {
  15. if (Input.GetMouseButtonDown(0) && !Input.GetKey(KeyCode.LeftShift))
  16. {
  17. var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  18. if (Physics.Raycast(ray.origin, ray.direction, out m_HitInfo))
  19. m_Agent.destination = m_HitInfo.point;
  20. }
  21. }
  22. }