Unity UI RectTransform position does not make sense to me

18,426

Solution 1

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!

Solution 2

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.

Share:
18,426
Catlard
Author by

Catlard

i am alive! alive!

Updated on June 13, 2022

Comments

  • Catlard
    Catlard almost 2 years

    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.

  • Catlard
    Catlard almost 9 years
    I found the problem! I was using anchoredposition and still had the problem. Good idea, though!