- Home /
Canvas Pivot in Screen Space Overlay
Hey all, I'm finally biting the bullet and moving my older projects to the new Unity UI (about time!), and I'm having a hard time with the pivot and anchor system. Here's what I want:
.
A UI element, generated at runtime through script, that is positioned such that its upper left corner is always in the upper left corner of the screen, even on screen resize.
.
Here's what I'm doing:
RectTransform rectButton = objElement.GetComponent<RectTransform>();
rectButton.sizeDelta = new Vector2(600, 200);
rectButton.pivot = new Vector2(0f, 1f);
rectButton.localPosition = GetRelativePos(main.canvasScreenUi.GetComponent<RectTransform>(), new Vector2(0f, 1f));
Where:
protected static Vector2 GetRelativePos(RectTransform parent, Vector2 positionRatios)
{
//Clamp the ratios
positionRatios.x = Mathf.Clamp(positionRatios.x, 0f, 1f);
positionRatios.y = Mathf.Clamp(positionRatios.y, 0f, 1f);
//Get the results
return new Vector2(parent.rect.width * (positionRatios.x - parent.pivot.x),
parent.rect.height * (positionRatios.y - parent.pivot.y));
}
Why am I doing this? Because the pivot point on the Canvas is set to (0.5,0.5) and that appears to be immutable so long as I'm in Screen Space - Overlay. Which is the mode I want, I think? I don't want my UI floating around in the 3D world or doing anything weird, I want it to be strictly confined to the 2D plane of the screen. If this isn't the mode I want for strictly screen-space UI, why not? If it is, why can't I adjust the pivot?
.
Because this is causing a second problem - while this puts the element where I want it initially, if I resize the screen, the element obviously remains at the exact same distance from the Canvas' pivot, which is the center of the screen. So if I widen the screen, for example, the button is now detached from the edge and closer to the center.
.
I'm sure there must be a way to deal with this with anchors or something, but I'm still completely unfamiliar with the system and I'm not seeing anything in the documentation that helps me understand what's going on.
.
TL;DR: How do I get script-generated UI elements to stick to the edge of the screen?
Your answer
Follow this Question
Related Questions
UNFIT SCREEN SIZE FOR MOBILE 0 Answers
Snap UI Text inside canvas 1 Answer
Render UI with RenderTexture to final render result 0 Answers