Skip to main content

Posts

Showing posts from March, 2016

Understanding unity UI through coding

Hello guys,

In this post i will be sharing what i learned about unity new UI system, i will start with smaller ones later i will keep adding new things to this post.

Before starting, i will assume that our Script is attach to an Image inside a canvas. You can use some of the one line codes, shown in this post inside your Start function to test the results.




1. How to get width and height of an UI element.

For Width use  : GetComponent<RectTransform>().rect.width;
For Height use : GetComponent<RectTransform>().rect.height;







2. How to move an UI element.

You can use this line of code to move a UI.

GetComponent<RectTransform>().anchoredPosition+=newVector2(10,0);

Before moving :


    After moving :


     As you can see the image have moved 10 units to its right side.

But,

     You can also notice, Image have moved, but Anchors are 'at there previous position'.

     I found one solution over Internet, to set Anchors position, it works very well.

     Pass any gameObject to …