Turning character slowly with Slerp

I make my character walk using a navmesh and when he arrived I would like him to turn towards the character he is in front of. I use the following function but I keep getting errors and I can’t get it to work.

public static IEnumerator TurnToFaceSmoothly (Transform targetThatWalks, Transform targetToLookAt) {
        while (Vector3.Dot (targetThatWalks.forward, (targetToLookAt.position - targetThatWalks.position).normalized) < 0.95f) {
            Vector3 dir = targetToLookAt.position - targetThatWalks.position;
            targetThatWalks.rotation = Quaternion.Slerp(targetThatWalks.rotation, Quaternion.LookRotation(dir), 5f * Time.smoothDeltaTime);
            targetThatWalks.eulerAngles = new Vector3(0f, targetThatWalks.eulerAngles.y, 0f);
            yield return null;

I call this function as following in my “static IEnumerator doWalkingAction()” method:

yield return StartCoroutine (TurnToFaceSmoothly (playerObj.transform, npcObj.transform));

Which gives me the following error:

error CS0120: An object reference is required to access non-static member `UnityEngine.MonoBehaviour.StartCoroutine(System.Collections.IEnumerator)’

I tried removing the static and calling the function just with:

TurnToFaceSmoothly (playerObj.transform, npcObj.transform);

However when I did this I noticed that the function never ever gets called, I put some debug.log’s in that turntofacesmoothly function and they never showed up (and obviously the turning did not happen as well)

What am i doing wrong? I cannot seem to figure it out, i’ve been stuck here for hours and hours.

You’re using coroutines statically but in your doWalkingAction you’re using playerObj which I think is (reading the exception message) a local member of the script. As the message states: you cannot use the class members directly in the static functions because they belongs to an instanced object. Your second try (calling directly the function without StartCoroutine) is wrong because if you call that way it’s not creating a “coroutine loop” (which is part of StartCoroutine) and instead it’s called just once.