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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With