So I needed a StartCoroutine in a static method, however since this is not possible I stumbled across a StaticCoroutine script (found here: http://benbeagley.com/2013/10/14/calling-a-static-ienumerator-in-unity/, original credits to user @whydoidoit).
The function I need to call makes the character turn towards another character he just walked to.
It is being called like this in my static IEnumerator method:
public static IEnumerator doWalkingAction() {
if (subject._noun == "player") {
setWalkerScript(playerObj);
if (npcNames.Contains(direct._noun.ToLower())) {
startMovingToNPC(direct._noun.ToLower());
bool walkingNotDone = true;
while (walkingNotDone) {
if (playerObj.GetComponent<AgentWalker>().arrivedOrNot()) {
npcObj = GameObject.Find(direct._noun.ToLower());
StaticCoroutine.DoCoroutine(turnToFaceSmoothly(playerObj.transform, npcObj.transform));
playerObj.GetComponent<Animation>().animation.Play("idle");
Destroy(playerObj.GetComponent("AgentWalker"));
walkingNotDone = false;
} else {
yield return new WaitForSeconds(0.5f);
}
}
yield return null;
}
} else {
}
}
And the code of ‘turnToFaceSmoothly’ looks like this:
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;
}
}
When running my game, I noticed that this turnToFaceSmoothly method gets called non-stop, giving of course a very undesirable result!
Why does it do this? Thank you in advance for anyone who can help