Drag and Drop

Hi everyone,
Im having a bit of an issue trying to implement a drag and drop system in my game. I watched a video on youtube http://www.youtube.com/watch?v=ZCKiuu1qcRY) of it in Javascript and it work perfectly but when i converted it to C# is just gave me 2 errors.

using UnityEngine;
using System.Collections;

public class Turret : MonoBehaviour 
{
    private Ray ray;
    private RaycastHit hit;

	// Use this for initialization
	void Start () 
    {
	
	}
	
	// Update is called once per frame
	void Update () 
    {
        OnMouseDrag();
	}


    void OnMouseDrag()
    {
        if (Input.GetMouseButton(1))
        {
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if(Physics.Raycast(ray, out hit))
            {
                transform.position.x = hit.point.x;
                transform.position.y = hit.point.y;
            }
        }
    }
}

im getting errors on the lines:

                transform.position.x = hit.point.x;
                transform.position.y = hit.point.y;

The errors say “Cannot modify the return value of ‘Unity.Engine.Transform.position’ because it is not a variable”.

I know that im probably doing something stupid but can anyone give me some advice?

Simple, its just as it says. try xxx.position =new vector3(x, y, z)
c# doesnt support assigning vector3 directly.

Ive just tried that and i replaced the (x, y, z) with values and the object just jumps to that location. However, I want to be able to hold down the mouse button and place the object where ever i want to place it. Any ideas?

Thanks for the reply.

try this

Vector3 pos = transform.position;
pos.x = hit.point.x;
pos.y = hit.point.y;

one of the problems is you have on mouse drag in update… it shouldnt be there its called as an event on the collider or gui element. if youre implementing a 3d object or 2d object there is a whole bunch of screen space world space and alignments youneed to look upin reference. you should be able to find most of your answersby googling it. also look at the script package included with unity. it handles basic drag and drop with unity

Okay thanks alot.

Store the value in Temporary variables …