Move CharacterController to Destination causes Unity to Crash

Hey there!

So i need to change some things what means i cant use NavMeshAgent for that,
so i got an CharacterController which should move from Point A to Point B,

i got a simple funciton which does that for me:

        public void MoveTowardsTarget(Vector3 target)
        {
            Vector3 destination = target - transform.position;
            if (destination.magnitude > .1f)
            {
                //Move to Direction
                destination = destination.normalized * MaxWalkSpeed;
                characterController.Move(destination * Time.deltaTime);

                //Look at Direction
                destination.y = transform.position.y;
                Quaternion targetRot = Quaternion.LookRotation(destination - transform.position, Vector3.up);
                transform.rotation = Quaternion.Slerp(transform.rotation, targetRot, Time.deltaTime * 2f);
            }
        }

if i put that one in the Update Loop it works but if i put that into a coroutine:

        IEnumerator test()
        {
            while (!isAtTarget(target.transform.position))
            {
                MoveTowardsTarget(target.transform.position);
            }
            yield return null;
        }

Unity Crashes … , anyone any idea?

As long as you’re in that while loop, nothing else is running.

Unity is single threaded from a scripts standpoint.

Put the yield return null inside the while loop.

2 Likes

Also, make sure isAtTarget() is tolerant enough to allow the object to get close but not exact, as you do not want to test floating point numbers for equality, as they often will never actually equal each other. Also, make sure it doesn’t get “not quite close enough” and then pass it.

Reading your code above, with enough walk speed this could happen. Instead, use this:

To prevent overrun.

2 Likes

Perfekt! Thanks

1 Like

and even better :smile:

1 Like