Certainly! Below is a simple Unity C# script that you can use to move a 3D character using a point-and-click system with a NavMesh. This script assumes you have already set up a NavMesh in your Unity scene, and your character has a NavMeshAgent component attached to it.
First, make sure to include the necessary namespaces at the top of your script:
csharp
using UnityEngine;
using UnityEngine.AI; // Necessary for NavMesh components
Here's the basic script:
csharp
public class PointAndClickMovement : MonoBehaviour
{
public Camera cam; // Assign your scene's main camera to this in the inspector
public NavMeshAgent agent; // Assign your character's NavMeshAgent component to this in the inspector
void Update()
{
if (Input.GetMouseButtonDown(0)) // Check for left mouse button click
{
Ray ray = cam.ScreenPointToRay(Input.mousePosition); // Cast a ray from the camera to the mouse position
RaycastHit hit;
if (Physics.Raycast(ray, out hit)) // Check if the ray hits a collider in the scene
{
agent.SetDestination(hit.point); // Set the destination for the NavMeshAgent to the hit point
}
}
}
}
Here's a step-by-step guide on how to use this script:
Create a NavMesh in your scene by going to Window > AI > Navigation and bake it according to your scene setup.
Attach a NavMeshAgent component to the character you want to move.
Create a new script named PointAndClickMovement and paste the code above into it.
Attach the PointAndClickMovement script to the same GameObject that has the NavMeshAgent, or another appropriate GameObject in your scene.
Drag your scene's main Camera to the cam field of the PointAndClickMovement script in the Unity Inspector.
Drag the character's NavMeshAgent component to the agent field of the PointAndClickMovement script in the Unity Inspector.
Press play, and you should be able to click on any point within your NavMesh to move your character to that location.
Make sure your character's NavMeshAgent component is configured correctly with suitable speed, acceleration, and other parameters to get the desired movement behavior. Also, ensure that the camera is correctly assigned to the script to correctly translate mouse clicks into