- Home /
fit UI prefab to screen
I need to instantiate a UI prefab and scale it to the screen size. I have tried:
modalInst.GetComponent<RectTransform>().anchorMin = new Vector2(0, 0);
modalInst.GetComponent<RectTransform>().anchorMax = new Vector2(1, 1);
modalInst.GetComponent<RectTransform>().pivot = new Vector2(0.5f, 0.5f);
modalInst.GetComponent<RectTransform>().offsetMin = new Vector2(0, 0);
modalInst.GetComponent<RectTransform>().offsetMax = new Vector2(0, 0);
This does not work. There must be a simple way to do this that I am overlooking.
sET cANVAS RENDER $$anonymous$$ODE TO SCALE WITH SCREEN?
Answer by unity_xeSLiO4zDpfDBg · Mar 01, 2020 at 10:57 PM
You want to use Canvas Scaler component on your camera game object. If your game is a horizontal game, adjust Match to 1 based on Height. This basically means that the scale of everything will be adjusted based on the resolution of height, which won't change across different devices for a horizontal game. If you want a vertical game, then change Match to 1 based on Width.
I am already using a canvas scaler. The issue is that when I instantiate a prefab, I need it to scale to the screen size. Right now it does not do this on its own. $$anonymous$$eaning, it will fit on some aspect ratios but not on others.
Hey, you either need to check if the parent of your cloned prefab has Layout Group, or you forgot to set a parent for your cloned prefab.