How to fix crash from force towards mouse script

I tried to put together something that makes a 2d rigidbody move toward the cursor, whenever the mousebutton is held down. It’s a derivative of the script from here: Loading...
It moves properly so long as nothing is clicked, but when the mouse is clicked the unity client freezes. This the code:

using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour
{

    public float speed; 
    private Vector2 endPoint;
    private Rigidbody2D rb2d;
    private Vector2 direction;


    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        do
        {
            RaycastHit hit;
            Ray ray;
            #if UNITY_EDITOR
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            #elif (UNITY_ANDROID || UNITY_IPHONE || UNITY_WP8)
            ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
            #endif
            if (Physics.Raycast(ray, out hit))
            {
                endPoint = hit.point;
                Debug.Log(endPoint);
            }
            rb2d.AddForce(endPoint * speed);
        } while (Input.GetMouseButton(0));
    }
}

Any solutions would be appreciated.

A common mistake of the ‘while’ loop. Anything that you put in while will infinitely repeat until the condition is no longer true. This is very different then putting something in Update, which checks every frame, but just once.

In your case, Input.GetMouseButton(0) is true in one frame, and then the while loop runs infinitely in a single frame (until Unity crashes) since there’s no condition for it to leave that while loop.

Try this:

if (Input.GetMouseButton(0))
{
             RaycastHit hit;
             Ray ray;
             #if UNITY_EDITOR
             ray = Camera.main.ScreenPointToRay(Input.mousePosition);
             #elif (UNITY_ANDROID || UNITY_IPHONE || UNITY_WP8)
             ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
             #endif
             if (Physics.Raycast(ray, out hit))
             {
                 endPoint = hit.point;
                 Debug.Log(endPoint);
             }
             rb2d.AddForce(endPoint * speed);
}