# How do I set the exact local position of a RectTransform?

I have a game object that creates a keyboard in side of my world canvas. I am working out the offset positions for each key, and appear to be doing that correctly. However, when I set the positions in the actual keys, the values are being offset by anything from 100 - 1000.

This is the basic method I am currently using to set the position:

public void SetDimensions(Vector2 position)
{
GetComponent<RectTransform>().localPosition = position;
Debug.Log(key + ": " + position);
}


I have also tried using .position and .anchoredPosition, as per the somewhat confusing API reference. I have also tried simply referencing transform.localPosition and transform.position. No matter what, the output is exactly the same. The debug output confirms that I am working out the correct local position, but no matter what I do, that is not the value being set to my transform.

As you can see, I have my pivot set to the center; though I think this may have an impact, it certainly should not cause an offset of 400-500.

As per request, this is my main canvas:

What am I doing wrong, or more specifically, how do I set the exact local position of a game object using a RectTransform?

• Please note that I am aware that there are built in keyboard functions. The specific purpose of this exercise is to make a keyboard, specifically because I want to. Mar 29 '17 at 7:43
• Can you also show us your canvas settings? Mar 29 '17 at 10:05
• @DMGregory, added as per request. I realise I didn't expand my anchors, but they are all set to (0,0). Mar 29 '17 at 10:43

First of all, ensure you set the parent before setting local position, then, you have two options according to the type of Rect Transform : non-stretching and stretching ones.

For a non-stretching Rect Transform, the position is set most easily by setting the anchoredPosition and the sizeDelta properties. The anchoredPosition specifies the position of the pivot relative to the anchors. The sizeDelta is just the same as the size when there’s no stretching.

Try to do as follow :

RectTransform rt = GetComponent<RectTransform>();
rt.anchoredPosition = position ;
Debug.Log( position + " " + rt.anchoredPosition ) ;


I've just tried the previous code with a simple button inside a canvas, it works great. If it doesn't for you, you may have another script changing the position or a parent with a Layout group maybe ?

RectTransform rt = GetComponent<RectTransform>();

• I already tried anchoredPosition, and the offset suggestion does nothing (at least, not in context). Mar 29 '17 at 10:40