I have a game object that lives in world space in my scene. I would like to get the coordinates of the corners of the bounding rectangle for this game object's renderer in screen space because I have UI elements that want to be positioned around this box.
Context: I'm making a tutorial and I am using panels to darken everything except for a game object that will be left un-darkened. I can do this easily with buttons that already live in screen space and have rect transforms on them, but I can't figure out how to do this around a game object in world space. We are using a camera with orthographic projection and are using Unity version 2019.2.17f1.
Here's what I've tried:
public void FocusOnRenderer(Renderer renderer) {
// left, top, right, and bottom are Panels whose pivots are set as follows:
// top: (1, 0)
// right: (0, 0)
// bottom: (0, 1)
// left: (1, 1)
// so when their positions are set to be the corners of the target bounding box, they will fit together nicely.
left.gameObject.SetActive(true);
top.gameObject.SetActive(true);
right.gameObject.SetActive(true);
bottom.gameObject.SetActive(true);
Vector3 center = HandleUtility.WorldToGUIPoint(renderer.bounds.center); // center of bounding box
Vector3 halfSize = HandleUtility.WorldToGUIPoint(renderer.bounds.extents)); // half size of bounding box
Vector3 topRight = center + halfSize;
Vector3 topLeft = center + new Vector3(-halfSize.x, halfSize.y, halfSize.z);
Vector3 bottomRight = center + new Vector3(halfSize.x, -halfSize.y, halfSize.z);
Vector3 bottomLeft = center + new Vector3(-halfSize.x, -halfSize.y, halfSize.z);
left.position = topLeft;
top.position = topRight;
right.position = bottomRight;
bottom.position = bottomLeft;
}
I think this is wrong because what I'm doing with the renderer's bounds to compute halfSize and center aren't giving me a bounding rectangle. I was hoping there would be an easy built in way to do this but I haven't been able to find anything so far.
Thank you for your help!