finding the size of a content size fitter

Hello out there in unity land~
I have a bit of code in which I have a Text object I’m using as a tooltip. It needs to have a fixed width but can have an arbitrary height. I have it’s size controlled by a Content Size Fitter with an attached Layout Element.
The Content Size Fitter is set to:
Horizontal Fit: preferred size
Vertical Fit: Min Size

My code needs to know the height of this object but when I call:

myNumber = this.GetComponent<RectTransform>().sizeDelta.y;

I find that myNumber is always 0.

So, if I can’t find size using sizeDelta, how should I find the size of something that is controlled by a content size fitter?

1 Like

I think you are looking for the rect of the RectTransform.

((RectTransform)transform).rect.height

That sizeDelta value is something else.

Worked like a charm! Thank you so much! I’d been stuck on that all day.

Hello,

so you used this code? :

myNumber = this.GetComponent<RectTransform>().rect.height;

I tried this variable and it seems to be the wrong one. In my project, its always 26. No matter how big the rect is.

Any ideas?

1 Like

You either never set new value or trying to get height right after setting, which is wrong because rect width\height is being recalculating in LateUpdate i guess.

So I’ve tried this as well and it doesn’t work for me. I’ve got an object with a vertical layout group and a content size fitter (vertical fit = min size). Its content is dynamically generated and appearing correctly. In the inspector during runtime it says its height is 200. But calling “subject.GetComponent().rect.height” returns 0. Any ideas?

2 Likes

Nevermind, turns out it is because it takes a frame to update its size and I was querying prior to that.

1 Like

Use
LayoutRebuilder.ForceRebuildLayoutImmediate

6 Likes

text.rectTransform.sizeDelta = new Vector2 (text.preferredWidth,text.preferredHeight);
backGround.sizeDelta = new Vector2 (text.preferredWidth+20.0f,text.preferredHeight+20.0f);