Move object to mouse click position

Hey folks,

So I’ve had some time away from Unity and I’ve come back to make quite a simple script but I keep getting tripping over my own code.

So basically I’ve got a couple of things going only, firstly I’ve got a Character object, nested within it I’ve got the main camera and also an object to hold the character model.

Outside of the Character object I’ve got an Empty Game Object called target.

Here’s what I want to do, wherever the player clicks the target object moves instantly to that position.

Now I’ve tried placing a simple script on the target object but it doesn’t appear to work.

using UnityEngine;
using System.Collections;

public class targetmove : MonoBehaviour {


	// Use this for initialization
	void Start () {

		Vector3 newPosition = transform.position;


	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetKeyDown(KeyCode.Mouse0)) 
		{
			if (Input.GetMouseButtonDown(0)) 
			{
				newPosition.x = Input.mousePosition.x;
				newPosition.y = Input.mousePosition.y;
				transform.position = newPosition;
			}
		}

	}
}

I know that ray casting may be a way to go but I’ve not used it that much and also when I tried it I had problems as my camera is nested within my character.

maybe it’s

using UnityEngine;
using System.Collections;
public class targetmove : MonoBehaviour
{
    Vector3 newPosition;
	void Start () {
        newPosition = transform.position;
	}
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {
                newPosition = hit.point;
                transform.position = newPosition;
            }
        }
    }
}

This is pretty simple. You can use the Vector3.Lerp function to achieve this. Use raycasting to get the mouse click position or the touch position. Then use the initial and the final position in the lerp function. The initial position being the position that the gameobject is at now and the final position being the click / touch position.
You can find the article by The Game Contriver on the same here

Move to Touch / Click Position - The Game Contriver