ClickedPointMovement.cs
using System.Collections; using UnityEngine; public class ClickedPointMovement : MonoBehaviour { public float speed = 30; RaycastHit hit; Camera mainCam; Coroutine _MoveCR; int layerMask; void Awake() { mainCam = Camera.main; layerMask = LayerMask.GetMask("Ground"); } void Update() { if (Input.GetMouseButtonDown(0)) { if (Physics.Raycast(mainCam.ScreenPointToRay(Input.mousePosition), out hit, 100, layerMask)) { if(_MoveCR != null) { StopCoroutine(_MoveCR); } _MoveCR = StartCoroutine(MoveToPosition(hit.point)); } } } IEnumerator MoveToPosition(Vector3 targetPoint) { targetPoint = new Vector3(targetPoint.x, transform.position.y, targetPoint.z); while (Vector3.Distance(transform.position, targetPoint) > 0.01f) { transform.position = Vector3.MoveTowards(transform.position, targetPoint, speed * Time.deltaTime); yield return null; } } }