Check if an object is changing position C#

Hello, how do I check if an object is changing position or not.
I wan’t to know this because I want to be able to do something, when an objects x position is getting greater, and I want to do something else when it’s getting smaller.

To monitor only the X coordinate of the object’s position, you could do this:

Vector3 lastPos;
Transform obj; // drag the object to monitor here
float threshold = 0.0f; // minimum displacement to recognize a 

void Start(){
  lastPos = obj.position;
}

void Update(){
  Vector3 offset = obj.position - lastPos;
  if (offset.x > threshold){
    lastPos = obj.position; // update lastPos
    // code to execute when X is getting bigger
  }
  else
  if (offset.x < -threshold){
    lastPos = obj.position; // update lastPos
    // code to execute when X is getting smaller 
  }
}

This will execute the code once when the X distance from the lastPos exceeds threshold. This also updates lastPos when the code is executed, thus the distance from this point must again exceed threshold for the code to be executed again.

This script is intended to be attached to another object; if you plan to use it in the monitored object, replace obj. in the text by transform. (or assign obj = transform; at Start).

Thank you for your answer Aldonaletto, I broke it down to read it so I figured I would re-post for future readers (see Below).

But I also wanted to point everyone to Transform.HasChange();
Which can be used similarly.

	Vector3 lastPos; 
	
	Transform obj; // drag the object to monitor here 
	
	float threshold = 0.0f; // minimum displacement to recognize.
	
	void Start(){ lastPos = obj.position; }
	
	void Update()
	{ 
		Vector3 offset = obj.position - lastPos; 
	if (offset.x > threshold){ lastPos = obj.position; 
	// update lastPos 
	// code to execute when X is getting bigger 
	} 
	else if (offset.x < -threshold)
	{ 
	lastPos = obj.position; 
	// update lastPos 
	// code to execute when X is getting smaller 
	} 
	} 
	/*This will execute the code once when the X distance from the lastPos exceeds threshold. 
	This also updates lastPos when the code is executed, thus the distance from this point must 
	again exceed threshold for the code to be executed again. 
	This script is intended to be attached to another object; 
	if you plan to use it in the monitored object, replace obj. in the text by transform. (or assign obj = transform; at Start).*/

3d object or all axis changing position with define threshold.

public float thresholdChange = 0.05f;
private Vector3 lastTransformPos;
private void Start()
    {
        lastTransformPos = transform.position;
    }
 
private void Update()
    {
        var diffVector = transform.position - lastTransformPos;
        if (diffVector.magnitude >= thresholdChange)
        {
            lastTransformPos = transform.position;
           //Do something 
        }
    }