Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity UI RectTransform position does not make sense to me

So, I'm using C# in unity to place some objects using Unity UI, and I have an object whose position in script is not the same as its position in the scene. I have the following code in a function:

using UnityEngine;
using System.Collections;

public class SeedChecker : MonoBehaviour {

    Vector3 lockedPos;
    RectTransform tran;

    // Use this for initialization
    void Awake () {
        tran = GetComponent<RectTransform>();
    }

    public void LockPos(Vector3 pos) {
        tran.localPosition = pos;
        lockedPos = pos;
        print (tran.localPosition);
    }

}

As an example, this code prints that its x position is -60 -- which is the correct number that I'm looking for -- 60 pixels to the left of the middle of the screen. But, when I look in the inspector and in the scene, the x position is 0 -- and the object is positioned exactly in the middle of the screen. This makes for a rather frustrating situation, which I've also talked about here. It's frustrating because it says it's getting the proper position, but when I assign this correct position to the object, it goes to what I think is the incorrect place. Is this a misunderstanding of how localpositions work in RectTransforms? My object is the child of a few objects, but all of them are zeroed to the center of the screen, and have "1" for scale values.

like image 815
Catlard Avatar asked May 07 '15 12:05

Catlard


2 Answers

As fas as I know, you should be using anchoredPosition. See the documentation for possible attributes: http://docs.unity3d.com/ScriptReference/RectTransform.html

I try to stay away from the inherited ones, because they give unexpected results if you don't fully understand how a RectTransform works.

like image 94
ohokke Avatar answered Oct 02 '22 04:10

ohokke


Solved it ! It turned out that my RectTransforms were behaving oddly because I was storing them in a class I wrote to keep them organized, called EventRow. Event row did not even inherit from MonoBehavior, but storing the RectTransforms in a System.Collections.Generic list inside that object caused them to position strangely. So, when I started storing them as children of other Rect Transforms, instead of keeping track of them in my EventRow class, it worked just fine! Strange, no? Have you ever seen anything like this? The original purpose of my EventRow class was to allow me to have a list of event lists -- a grid of events. My guess is that RectTransform doesn't like being a list of lists of this variety, and that it somehow cares about whether it's in a collection or not. Go figure!

like image 43
Catlard Avatar answered Oct 02 '22 06:10

Catlard