How do I calculate speed of an object in Unity?

Calculating Speed in Unity

In Unity, you need the distance an object travels and the time it took to travel that distance to calculate the speed. Here is a simple way:


Code Sample

          Vector3 previousPosition; // Store the object's position from the last frame    float speed; // This will be the calculated speed    void Update() {                speed = (transform.position - previousPosition).magnitude / Time.deltaTime;         // Use Time.deltaTime to get the time since the last frame        // Use Vector3's magnitude method to get the distance covered                previousPosition = transform.position;         // Update previous position to this frame's position for the next calculation    }    

This code calculates the speed of an object in game units per second.