Unity C# Yield / Dragging Game Objects

I’m attempting to use the script found here (How to drag gameobject with mouse - Questions & Answers - Unity Discussions) to drag objects around. I’m converting it to C#, however and I’m not sure what I need to do to get the yield statement to play nicely. Here’s my current code:

    void OnMouseDown() {
        Vector3 screenSpace = Camera.main.WorldToScreenPoint(transform.position);
        Vector3 offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));

        while (Input.GetMouseButton(0)) {
            Vector3 curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
            Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset;
            transform.position = curPosition;
            //YIELD GOES HERE - How do I do this in C#?
        }
    }

Any ideas? Not using a yield results in crashing Unity. Thanks in advance for your help!

The simple answer is you can only yield inside a coroutine. A coroutine need to return an IEnumerator. So your script should look like this:

IEnumerator OnMouseDown()
{
    Vector3 screenSpace = Camera.main.WorldToScreenPoint(transform.position);
    Vector3 offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
    
    while (Input.GetMouseButton(0))
    {
        Vector3 curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
        Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset;
        transform.position = curPosition;
        yield return null;
    }
}

Take a look at this page about coroutines. Read it carefully and keep in mind that you can switch the code examples to C# :wink:

yield return null;
@Razion