How could I make a label comes after a small gap from another label. Lets say I have two UI labels, and on runtime I edited them both, now what I want is that one label should come just after another like this :
SomeLabel somelabel OR mynameisthis helloWorld
Above ‘SomeLabel’ and ‘mynameisthis’ are referred to first label and ‘somelabel’ and ‘helloWorld’ are referred to another label.
Please help me here, as I could not find out at how much distance should I have to move the second label to exactly get what I want.
Whether it’s labels, a slot in your inventory or any other widget, the idea is the same:
Get the width of the first label.
Offset the 2nd label by the width of
the first one + the space between
them (set by you, I don’t know why you wanna ‘find’ it, there’s nothing to find).
Now, getting the width depends on how you set your scaling in your UIRoot, which is always been confusing for me.
But I always managed to get around getting the width of my widgets on-screen using NGUIMath.CalculateAbsoluteWidgetBounds(Transform t) - For convenience, I’ve written a method to get me the dimensions of a widget in screen-coords, the idea is to get the bounds of your object (which could be from a collider, renderer or if all fails, it drop back to the method I told you about), subtract max-min (in screen coords) to get the dimensions:
public static Vector3 GetObjectScreenDims(Transform trans, Camera cam)
{
var collider = trans.collider;
Bounds bounds;
if (collider != null)
bounds = collider.bounds;
else
{
var renderer = trans.renderer;
if (renderer != null)
bounds = renderer.bounds;
else bounds = NGUIMath.CalculateAbsoluteWidgetBounds(trans);
}
var sMax = cam.WorldToScreenPoint(bounds.max);
var sMin = cam.WorldToScreenPoint(bounds.min);
return sMax - sMin;
}
‘cam’ is the camera that you’re using in your UI.
So now to position the labels:
float space = 10f; // space between labels
// get the dimensions of the first label in screen-coords - all we care about here is the width
Vector3 L1_Dimensions = GetObjectScreenDims(label1.cachedTransform, guiCam);
// set the position of the 2nd label to the first one, so that we can offset it easily
label2.cachedTransform.position = label1.cachedTransform.position;
// get the position of the 2nd label in screen coords
Vector3 L2_ScreenPos = guiCam.WorldToScreenPoint(label2.cachedTransform.position);
// offset it, by the amount we discussed
L2_ScreenPos += (space + L1_Dimension.x);
// finally, set the new coords
label2.cachedTransform.position = guiCam.ScreenToWorldPoint(L2_ScreenPos);
If you did everything correctly, it should work. - You might need to debug for some time, if you get some wrong values. - Let me know how it goes, good luck! Happy NGUIng