My speed determining script is acting weird, please take a look at it.

My script is supposed to determine the speed at which an AI is going and give that information to my animation state machine. But for some reason in the scene I’m testing in the speed will read just fine for about a second and then it’ll read zero. In other scenes it will read always read zero, and in others it works just fine.

using UnityEngine;
using System.Collections;

public class BurlapAni : MonoBehaviour 
{
	public static Vector3 currVel;
	Vector3 prevPos;

	public void Update()
    {   
		SageLibrary_GameController controller = gameObject.GetComponent<SageLibrary_GameController>();
		
  		prevPos = transform.position;
  		StartCoroutine( CalcVelocity(prevPos) );
		controller.SetFloat("Speed", currVel.magnitude * 8);
    }

	IEnumerator CalcVelocity( Vector3 pos )
	{
		yield return new WaitForEndOfFrame();
		currVel = (pos - transform.position) / Time.deltaTime;
	}
}

I just found that if I disable another script, it fixes the problem. I have no idea why it would cause a problem.

using UnityEngine;
using System.Collections;

public class BurlapSpawner : MonoBehaviour {
	
	public float timeTillSpawn;
	public float timer;
	public GameObject spawnObject;
	
	private bool go = false;
	
	void Start () 
	{
		timer = 0;
	}
	
	void Update () 
	{
		if (go)
		{
			timer += Time.deltaTime;
			if (timer >= timeTillSpawn)
			{
				Instantiate(spawnObject, transform.position, transform.rotation);
				timer = 0;
				gameObject.active = false;
			}
		}
	}
	
	void OnTriggerExit(Collider other) {
        if(other.gameObject.tag == "Player")
		{
			go = true;
		}
    }
}

There seems to be some extra complexity in there that might be making calculations at the wrong time. If my memory isn’t completely shot, Update might be able to fire at times other than once per frame.

I’ve always just used:

private Vector3 lastPos;

public void Update() {
  velocity = (transform.position - lastPos) / Time.deltaTime;
  // do whatever movement stuff
  lastPos = transform.position;
}
// then physics does whatever movement stuff
// and next time you hit update, velocity is updated

Thanks. Simpler code is always good, but do you know why the other script might be causing it to not work?