How to fit a camera Viewport Rect to a UI Panel

Hello,

I’m trying to get the viewport rect of multiple cameras to fit exactly in line with some UI panels rendered on the screen. I feel like I’m close but I’m missing some offset of some sort that I just can’t work out.

Here is a picture of how it’s displaying currently:

And here is the code I’m using to set up the viewport rect. viewCam is the camera assigned to this “button” and parentPanelGO is the panel that contains the grid of “buttons”.

void Update(){
		if (parentPanelGO != null) {
			Rect rekt = viewCam.rect;
			Vector2 rectPos = rekt.position;
			rectPos.x = Mathf.Abs (Mathf.Abs (gameObject.GetComponent<RectTransform> ().anchoredPosition.x) / Mathf.Abs (parentPanelGO.GetComponent<RectTransform> ().rect.size.x));
			rectPos.y = Mathf.Abs (Mathf.Abs (gameObject.GetComponent<RectTransform> ().anchoredPosition.y) / Mathf.Abs (parentPanelGO.GetComponent<RectTransform> ().rect.size.y));
			rekt.position = rectPos;
			viewCam.rect = rekt;
		}
	}

I’m trying to calculate the viewport rect x and y by using the screen coordinates of the “button” divided by the size of the parent rect (since the viewport rect is a percentage of the screen).

Does anyone know if there is an easy way to convert a UI objects screen position to a percentage of the screen so that I can achieve this affect?

Also, is this a bad approach to this problem? Should I scrap this idea and just move the UI into world space so that I can position these screens more easily and only use 1 camera?

Thanks

You can always render cameras to the ender textures and then use Raw Texture component in your UI to display the cameras. Then you will only need to calculate the resolution to not have everything pixelated or have too high resolution (performance problems).