Correct scaling for a Target Box?

So basically I have a target box that is drawn as a GUI texture around a target gameObject. The texture is a simply square frame, dimensions of 128 x 128. The following code handles how it is drawn, and is attached to the camera object:

    var targetBox : Texture2D;
    var targetBoxH : float = 128;
    var targetBoxW : float = 128;
    private var lockPosition : Vector3;
    private var distanceToPlayer : float;
    var scalingFactor : float;
    var target : GameObject
    function Update(){
    //all this does is finds the camera, and transfers the position data to a point on the screen.
    lockPosition = GameObject.FindGameObjectWithTag("MainCamera").GetComponent(Camera).camera.WorldToScreenPoint(target.transform.position);
    //This finds the distance between the camera and the target object.
    distanceToPlayer = Vector3.Distance(GameObject.FindGameObjectWithTag("MainCamera").transform.position, target.transform.position);
    function OnGUI(){
    //Draws the target box around the target, and scales according to the distance and a seperate scaling factor.
GUI.DrawTexture(Rect(lockPosition.x - (targetBoxW/2)/(distanceToPlayer * scalingFactor), Screen.height - lockPosition.y - (targetBoxH/2)/(distanceToPlayer * scalingFactor), targetBoxW / distanceToPlayer / scalingFactor, targetBoxH / distanceToPlayer / scalingFactor),targetBox,ScaleMode.ScaleToFit, true,0);

The problem is that the target box doesn’t scale to fit around the target object nicely. If the target object is too big/too close, the texture doesn’t encompass the entire object within it. If the object is too far/too small, there are empty gaps between the edge of the target object and the edge of the texture box.

So how can I set it so that the texture box wraps neatly around the target object’s image on the screen?

The target object is player-picked and can be different objects with different sizes. Hence, I would expect the aspect ratio of the target box to change as well.

You can find the 2 furthest away points on the target objects by calculating the 8 points of its bounding box based on its Unity - Scripting API: Mesh.bounds and then converting them to screenspace and then iterate through them to find the two points that are furthest away from eachother to know how big your target box needs to be.

You can find an implementation of parts of what I just mentioned, here:

Read code under: “Edit: Here’s a better implementation that accounts for rotation and scale:” where you get an easy min and max of a 2d bounding box that you can use for your target box size.