[UNSOLVED] Get a GameObject width and height in pixels (JS)

I’m trying to put a button directly on a 2d GameObject, and I need to get the pixel width and height of the object that is underneath to properly size the button. Is there any way to get that?


Size in Unity is measured with units, not pixels. You can use Mesh.bounds to get the bounds of an object’s mesh.

Perspective or Orthographic camera? Can we assume anything about the nature or rotation of the game objects?

In general you can get something close by converting a bounds into screen points and then finding the maximum and minimum X and Y values.

  • Use either the corners of the renderer.bounds of the object or use the mesh.bounds and then convert the eight corners from local to world coordinates.
  • For each of the eight corners, do a WorldToScreenPoint().
  • Cycle through the resulting positions and find the minimum/maximum x and y
  • Subtract min from max to get the width and height

Here is an answer that with just a bit of modification will give you those values. ‘width’ and ‘height’ on lines 43 and 44 are what you are looking for:

Note for particular setups, you may be able to do the calculations with less work.

Try this Maybe it wil work and maybe i forgot something

#pragma strict

var gameObject1 : Transform;
var gameObject2 : Transform;

var gO1X : float; 
var gO1Y : float;
var gO1Z : float;

function Update()
    gO1X = gameObject1.transform.position.x;
    gO1Y = gameObject1.transform.position.y;
    gO1Z = gameObject1.transform.position.z;

        gameObject2.transform.position.x = gO1X;
        gameObject2.transform.position.y = gO1Y;
        gameObject2.transform.position.z = gO1Z;

in the gameObject1 put the transform of your first gameobject and on the gameObject2 the transform of your second gameObject

cheers skullbeats1