The question is answered, right answer was accepted
How to move UI element inside of canvas programmatically
I am trying to move element in UI canvas programatically but to no avail.
Here is my setup: http://i.imgur.com/H8JjfYS.jpg
Here is the code with which im trying to move it to the middle bottom of the screen:
Hp0 = GameObject.Find("Hp0").GetComponent<RectTransform>();
Hp0.anchorMax.Set(0.5f,0f);Hp0.anchorMin.Set(0.5f,0f);
this is called in a method that is part of Start() Does anyone know how to do this?
UPDATE: thing is that the Unity's Set method in anchorMax / Min does not work. It needs to be set like this:
Hp0.anchorMax = new Vector2(0.5f,0f); Hp0.anchorMin = new Vector2(0.5f,0f);
With anchorMax/Min you can set the anchor relative to the canvas size where the values range from 0 to 1. In this case new Vector2(0.5f,0f) is the bottom middle of the screen, new Vector2(0f,0f) would be bottom left of the screen etc.
From this point you can use
Hp0.anchoredPosition = new Vector2(0,0);
which sets position in pixels relative to the anchor you set before. The new Vector2(0,0) means that the UI element you are moving will be positioned in the center of the anchor. If you use new Vector2(53,20) it will be positioned 53 pixels to the right and 20 pixels to the top from the anchor. You can use negative values here to go towards left side / bottom from the anchor.
Follow this Question
Related Questions
How to tell if a RectTransform is within the visible area of a ScrollRect 1 Answer
null reference exception with text 0 Answers
Why do my UI buttons keep breaking? 1 Answer
Can't update score text - small error breaks the game (Space Shooter Tutorial) 1 Answer
How to create a difficulty slider/setting for a unity game in a setting scene 1 Answer