Search Unity

Sharing A Simple Click To Move Script

Discussion in 'Scripting' started by SimplyZak, Sep 3, 2015.

  1. SimplyZak

    SimplyZak

    Joined:
    Sep 2, 2015
    Posts:
    3
    Hello Everyone,

    I've been using unity for about a year now off and on when I can, I just wanted to share this simple click to move script that I made that uses nav mesh. I created this script because every time I found a script for click to move the player would just run into things and try to run through them. Feel free to use it as you wish. Anything you can think of to make this code run better would be awesome just leave it in the comments.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class ClickToMove : MonoBehaviour {
    5. //This script requires the player to have a NavMeshAgent component.
    6. //The functionality of ClickToMove will not work if the scene does not have a baked nav mesh.
    7. //You can edit player move speed via the NavMeshAgent component in the inspector.
    8.  
    9.     NavMeshAgent playerAgent; //This is where the players NavMeshAgent is stored.
    10.  
    11.     void Start () {
    12.         //The game will retrieve the NavMeshAgent component for you here.
    13.         playerAgent = GetComponent<NavMeshAgent> ();
    14.     }
    15.    
    16.  
    17.     void Update () {
    18.         //Every frame the game will check to see if the player has released LMB and then call MouseClick.
    19.         if(Input.GetMouseButtonUp (0)){
    20.             MouseClick ();
    21.         }
    22.     }
    23.  
    24.     void MouseClick (){
    25.         //A raycast will be directed towards the mouse position, stored and then the playerAgent will move towards the hit point.
    26.         RaycastHit hit;
    27.         Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    28.        
    29.        
    30.         if(Physics.Raycast (ray, out hit, 1000)){
    31.             playerAgent.SetDestination (hit.point);
    32.         }
    33.     }
    34. }
     
    JoeStrout likes this.
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    That's neat. I've never quite got around to using NavMeshAgent before; I had no idea it was so simple to get started!
     
    SimplyZak likes this.
  3. SimplyZak

    SimplyZak

    Joined:
    Sep 2, 2015
    Posts:
    3
    Hey JoeStrout,

    Thanks, learning NavMesh really helps with the click to move system, but is annoying in any other kind of system, in my opinion at least.

    If you're thinking about trying it out I have another post on how to use mechanim to animate NavMeshMovements.