简体   繁体   中英

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

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;
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM