Wednesday, June 17, 2015

unity - 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().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.


Console reports a value of (-127.3, -301.6), but the Inspector reports a value of (-660.358, -842.0745).


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?



Answer



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();
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 ?




For your information :



For a stretching Rect Transform, it can be simpler to set the position using the offsetMin and offsetMax properties. The offsetMin property specifies the corner of the lower left corner of the rect relative to the lower left anchor. The offsetMax property specifies the corner of the upper right corner of the rect relative to the upper right anchor.



RectTransform rt = GetComponent();
rt.offsetMin = rt.offsetMax = Vector2.zero ;


Source : https://docs.unity3d.com/Manual/HOWTO-UICreateFromScripting.html


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...