Use of unassigned local variable "prevPos"?

This code is supposed to be code for picking up objects, but it just gives me this error on line 29: Use of unassigned local variable ‘prevPos’

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Pickup_cube : MonoBehaviour {

    //this decides when you are holding the cube
    public bool holding;
    public Rigidbody rb;


    void OnMouseDown()
    {
        holding = true;
    }

    void OnMouseUp()
    {
        holding = false;
    }

    void Update()
    //this decides what the cube will do when you are holding it
    {
        Vector3 prevPos;//cached position

        //calculating and applying the force
        Vector3 dist = transform.position - prevPos;
        float time = Time.deltaTime;
        rb.AddForce((dist/(time * time)) *rb.mass);

        //caching position
        prevPos = transform.position;
        if (Input.GetButtonDown ("Fire2")) {
               
        }
        if (Input.GetButtonUp ("Fire2")) {
           
        }
        if(holding == true)
        {
            this.transform.SetParent(Camera.main.transform);
            Rigidbody Rigidbody = gameObject.GetComponentInParent<Rigidbody>( );
            Rigidbody.useGravity = false;
            Rigidbody.drag = 100;
            Rigidbody.isKinematic = false;
        }
        if(holding == false)
        {
            this.transform.parent = null;
            Rigidbody Rigidbody = gameObject.GetComponentInParent<Rigidbody>( );
            Rigidbody.useGravity = true;
            Rigidbody.drag = 0;
            Rigidbody.isKinematic = false;
        }
    }
}

You need to initialized prevPos.

Change:

Vector3 prevPos;

to:

Vector3 prevPos = new Vector3(0, 0, 0);

Thank you so much!

That will make the error go away. But the code probably won’t function as desired.

It looks like the intent is to have previousPos as a class variable. So move the declaration on line 25 up to line 10.

What do you mean “cached position”? Is this something that needs to be persisted from the previous frame? Then declare it at the class level.