Finding how big/small an object has become ( its scale) after modifying its z-depth ( in a 2D perspective camera)

I have set up a parallax scrolling effect on my 2D game using the perspective camera approach. However, when I alter my pixel-art sprite’s z-position, their sizes ( or scale or whatever it’s called) also changes ( due to the nature of perspective cameras).
What I’d like to do is adjust their scales based on how far/near my sprites are to the camera, in order to maintain the pixel-perfect look on those backgrounds.

In order to do that I will be attaching a script on each background prefab in order to adjust its scale on the Start() function. What’s left for me to do is finding the equation that relates the scale with the z-position of the object. After finding the scale, I’d simply unscale the object by that amount to seem pixel-perfect yet again.

I’m unable to find that equation, so if anyone could do the math behind it, I’d be thankful !

Assuming you are not changing the field of view, and assuming you have a standard setup where the camera’s rotation is (0,0,0), then you can do this:

#pragma strict
 
private var startScale : Vector3;
private var startDist : float;
private var lastDist : float;
 
function Start() {
	startScale = transform.localScale;
	startDist = transform.position.z - Camera.main.transform.position.z;
	lastDist = startDist;
}
      
function Update() {
	var dist = transform.position.z - Camera.main.transform.position.z;
	if (dist != lastDist) {
		transform.localScale = startScale / startDist * dist;
		lastDist = dist;
	}
}

This will keep your object as the same size regardless of its distance from the camera.