Unity UI RectTransform doesn't make sense to me

So, I am using C # in unity to place some objects using the Unity UI and I have an object whose position in the 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 out that its x position is -60 - which is the correct number 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 located exactly in the middle of the screen. This leads to a rather unpleasant situation, which I also mentioned. This is frustrating because it says it is getting the correct position, but when I assign that correct position to the object, it jumps to what I think is the wrong place. Is it a misunderstanding of how local objects work in RectTransforms? My object is a child of several objects, but they all zero to the center of the screen and have a "1" for the scale values.

+3


source to share


2 answers


I decided! It turned out that my RectTransforms were behaving strangely because I was storing them in a class I wrote to organize them called EventRow. The event line didn't even inherit from MonoBehavior, but keeping the RectTransforms in the System.Collections.Generic list inside this 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 great! Strange, no? Have you ever seen something 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 to be a list of lists of this sort, and that it somehow cares about whether it's in the collection or not. Go figure!



+1


source


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 legacy ones because they give unexpected results if you don't fully understand how it works RectTransform

.

+4


source







All Articles