- Home /
Unity crashing on creation of while loop
This is my code and i need some help. I try to make my gameobject move to the mouse cursor but only when i click and not hold the button.
private void Update()
{
if (Input.GetMouseButton(0))
{
moving = true;
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100.0f))
{
while (moving == true && transform.position != hit.point)
{
transform.position = Vector3.MoveTowards(new Vector3(transform.position.x,3f,transform.position.z), hit.point, movementSpeed * Time.deltaTime);
if (hit.point == transform.position)
{
moving = false;
}
}
}
}
}
}
Answer by ProtoTerminator · Aug 14, 2018 at 07:40 PM
Change while
to if
. Set moving to false before the raycast, and true inside the changed if.
Also, it never breaks out of the loop since you set the start Y value to 3f while leaving the target Y value as whatever the raycast returns.
Well is helped me but i still want the walking of the character to work in this way. If i click anywhere on my flat ground it will move there and i dont have to either keep clicking to make if move or hold mouse button down
Oh, so the movement will only happen when you click and not hold, right? You don't want to be able to drag your mouse around and have it keep moving? If so, you can simple change Input.Get$$anonymous$$ouseButton(0)
to `Input.Get$$anonymous$$ouseButtonDown(0). This will make so this will only happen once when the mouse button goes down. Hopefully that's what you're looking for.
Answer by Hellium · Aug 15, 2018 at 08:55 AM
private IEnumerator moveCoroutine = null ;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100.0f))
{
if( moveCoroutine != null )
StopCoroutine( moveCoroutine ) ;
moveCoroutine = MoveToTarget( hit.point ) ;
StartCoroutine( moveCoroutine ) ;
}
}
}
private IEnumerator MoveToTarget( Vector3 target )
{
while (( transform.position - target ).sqrMagnitude < 0.01f )
{
transform.position = Vector3.MoveTowards(new Vector3(transform.position.x,3f,transform.position.z), target, movementSpeed * Time.deltaTime);
yield return null ;
}
moveCoroutine = null ;
}
Your answer
