Unity freezes every time I press the play button


Unity freezes when I press play after adding the PlayerController script to my character. Here is my code:

using System.Collections;
using System.Collections.Generic;
using Unity.Jobs;
using UnityEditor.UIElements;
using UnityEngine;

public class NewMonoBehaviourScript : MonoBehaviour
{
public float moveSpeed;

private bool isMoving;

private Vector2 input;

private void Update()
{
    if(!isMoving)
    {
        input.x = Input.GetAxisRaw("Horizontal");
        input.y = Input.GetAxisRaw("Vertical");

        if (input.x != 0) input.y = 0;

        if (input != Vector2.zero);
        {
            var targetPos = transform.position;
            targetPos.x += input.x;
            targetPos.y += input.y;

            StartCoroutine(Move(targetPos));
        }
    }
}

IEnumerator Move(Vector3 targetPos)
{   
    isMoving = true;
    while((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon);
    {
        transform.position=Vector3.MoveTowards(transform.position, targetPos, moveSpeed*Time.deltaTime);
        yield return null;
    }
    transform.position = targetPos;

    isMoving = false;
}

}

You can rewrite this as:

while(true);

Does the same thing. :wink:

That thing being an infinite loop. Or so I thought … there’s a yield there as well, so it should only infinitely run the coroutine every frame.

Regardless, don’t use a coroutine. You can inline that code directly in Update and it’ll be much, much easier to work with! Coroutines are a trap most of us have fallen into, it’s just a matter of how quickly you come to see how much easier life without coroutines actually is.