Explorer
Explorer

Reputation: 1

Drag and Drop C# (Unity 2D)

So I am a newbie Unity dev and am making a game that involves a drag and drop system, I watched a tutorial and got help from a friend but it won't work... an error I get is it says public isn't valid or what ever, same for private.

public class Draggable : MonoBehaviour
{
Vector2 difference = Vector2.zero;
}
private void OnMouseDown()
{
difference = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
}
private void OnMouseDrag()
{
transform.position = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition) - difference;
}

here is a picture of the error

Upvotes: 0

Views: 1053

Answers (2)

KiynL
KiynL

Reputation: 4266

Your functions are written outside the class. Correct the parentheses.

public class Draggable : MonoBehaviour
{
    Vector2 difference = Vector2.zero;
    private void OnMouseDown()
    {
        difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
    }

    private void OnMouseDrag()
    {
        transform.position = (Vector2) Camera.main.ScreenToWorldPoint(Input.mousePosition) - difference;
    }
}

Upvotes: 1

Mario
Mario

Reputation: 714

Your Methods are outside the scope of the class, ensure of move then into the body of your class inside the block "{ }"

Upvotes: 0

Related Questions