Hello,
in my inventory system, I want to be able to determine the number of rows/columns I have based on the height/width on my inventory background and the slots size. (See attachment)
So like, if I had a 500x500 background, with a slot size of 50, I will have 10x10 2d inventory.
Problem is, I can't seem to do that the right way! Here's what I'm doing:
1- The slot size is set in the bag from the inspector (like 50 for example)
2- When I create the slot at run time, I have to figure out its right scale right?
This is what I'm doing for that (basically I'm following the formula: newScale = (newSize * currentScale) / currentSize):
realPixelScale
= NGUITools
.Get3dPixelScale(background
.cachedTransform,
new Vector2
(SlotSize, SlotSize
));
Where (please don't get lost, it's simple):
public static Vector3 Get3dPixelScale(Transform trans, Vector3 newSize)
{
var currentSize = GetObjectScreenDims(trans);
return Get3dPixelScale
(currentSize,
new Vector2
(newSize
.x, newSize
.y), trans
.localScale); }
// Gets an object dimensions in screen coords
public static Vector3 GetObjectScreenDims(Transform t)
{
var cam = FindCameraForLayer(t.gameObject.layer);
var bounds = GetObjectBounds(t);
var sMax = cam.WorldToScreenPoint(bounds.max);
var sMin = cam.WorldToScreenPoint(bounds.min);
return sMax - sMin;
}
public static Vector3 Get3dPixelScale(Vector3 currentSize, Vector3 newSize, Vector3 currentScale)
{
Vector3 newScale = Get2dPixelScale(currentSize, newSize, currentScale);
newScale.z = (newSize.z * currentScale.z) / currentSize.z;
newScale.z = Mathf.Clamp(newScale.z, 1, newScale.z);
if (float.IsNaN(newScale.z))
newScale.z = 1;
return newScale;
}
public static Vector2 Get2dPixelScale(Vector2 currentSize, Vector2 newSize, Vector2 currentScale)
{
var newScale
= new Vector3
(); newScale.x = (newSize.x * currentScale.x) / currentSize.x;
newScale.x = Mathf.Clamp(newScale.x, 1, newScale.x);
newScale.y = (newSize.y * currentScale.y) / currentSize.y;
newScale.y = Mathf.Clamp(newScale.y, 1, newScale.y);
return newScale;
}
So now, I 'should' have the right scale for the slot, such that its height and width are 'SlotSize'
Now, in my bag:
var dims = NGUITools.GetObjectScreenDims(background.cachedTransform);
nMinCols = (int)(dims.x / slotSize);
nMinRows = (int)(dims.y / slotSize);
It doesn't work

- For some reason, I get more slots than I should (the slot is getting a higher scale than it should. ex: I give it a 60 size, I get a scale of (70, 70, 1)

- I am 100% sure that for some reason, this script used to work just fine with me, but now it's not...
What is the right way to do what I want? what should I calculate, what should I divide?... please any help would be appreciated - thanks a lot.
and please let me know if I'm doing something bad / the wrong way (bad habit - miss-use)
Note that I do get better results if I just say:
realScale
= new Vector3
(slotSize, slotSize,
1); // instead of all that long calculations
But sometimes this could cause problems in other places :/