Click To Move (should be an easy one)

I thought I'd get my hands dirty with some Unity Javascript but I seem to be falling at the first hurdle. I blatantly and unashamedly took this code from these very forums but need some help getting it to run.

I get an Object ref not set to object error around these lines: var ray = Camera.main.ScreenPointToRay (Input.mousePosition); if(Physics.Raycast(Camera.main.transform.position, ray.direction, hit, 1000, layerMask)) but can't for the life of me figure it out. I've attached this code to a character placeholder (couple of bricks) with the hopes of having my 3rd person click to move.

    private var move : boolean = false;

function Update () 
{ 
    if (Input.GetButtonDown ("Mouse Left")) 
    { 
        var ray = Camera.main.ScreenPointToRay (Input.mousePosition); 
        if(Physics.Raycast(Camera.main.transform.position, ray.direction, hit, 1000, layerMask))
        { 
         move = true ; 
        } 
    } 

    if(move) 
    { 
        var wantedPosition= Vector3(hit.point.x, hit.point.y, hit.point.z); 
        transform.LookAt(wantedPosition); 
        transform.position = Vector3.Lerp(transform.position, hit.point, Time.time/200); 

        if(Vector3.Distance(transform.position, wantedPosition) < 0.01) 
        { 
            move = false; 
        } 
    } 
}

Any clues?

Camera.main needs a camera tagged "MainCamera" in order to find anything.

I got it to work with the following adjustments:

  • define a RaycastHit object for info to be stored in
  • get rid of the layermask (or define on)
  • also, you need an object where you click the mouse, so it can get a position off. Terrain won't do apparently...

    private var move : boolean = false; var hit : RaycastHit;

    function Update () { if (Input.GetButtonDown ("Fire1")) { var ray = Camera.main.ScreenPointToRay (Input.mousePosition); if(Physics.Raycast(Camera.main.transform.position, ray.direction, hit, 1000)) { move = true ; } }

    if(move) 
    { 
        var wantedPosition= Vector3(hit.point.x, hit.point.y, hit.point.z); 
        transform.LookAt(wantedPosition); 
        transform.position = Vector3.Lerp(transform.position, hit.point, Time.time/200); 
    
    <pre>`if(Vector3.Distance(transform.position, wantedPosition) < 0.01) 
    { 
        move = false; 
    } 
    
    

    }
    `

    }