- Home /
How to snap UI element anchor relative to image sprite?
I have a UI panel and it contains UI images, I want to make that every time when I create new instance of image, that instance had the anchor relative to image sprite. Image sprite size can change, and I know that I have to use RectTransform.anchorMax and RectTransform.anchorMin, but cannot find solution.
What it is
What I want
Answer by Gurunext · Aug 29, 2020 at 04:00 AM
I need the same thing and "sorry to say Unity sucks" doesn't work for me - the worse thing if you try to do a code for this changing anchor position will change image/sprite position too...
Here's how much code you need to perform this function. You can create some editor addon or just like me use [ExecuteInEditMode] select your target and run this exact script on it.
RectTransform rt = target.GetComponent<RectTransform>();
Vector2 pos = rt.transform.position,
size = new Vector2(rt.rect.width, rt.rect.height)/2,
pos1 = pos - size, pos2 = pos + size;
rt.anchorMin = new Vector2(pos1.x / Screen.width, pos1.y / Screen.height);
rt.anchorMax = new Vector2(pos2.x / Screen.width, pos2.y / Screen.height);
rt.anchoredPosition = new Vector2(0, 0);
rt.sizeDelta = new Vector2(0, 0);
Answer by Developer061 · Jan 06, 2020 at 06:31 AM
Sorry to say but you have to do it manually for each sprite, The proper way is 1. to reset the rect transfrom of the UI Image and 2. press the setNative button, it will be centered with the original size of the sprite 3. Set the Anchors manually
Btw it can be set to the anchors of the Parent by from the inpector
Your answer
Follow this Question
Related Questions
Why is Sprite a null? 0 Answers
How to make a UI image change sprite through a script that is not attached to the UI image itself 0 Answers
Error facebook profile picture 1 Answer
Ui scaling 1 Answer
Loading built-in resources 1 Answer