I can't get the preferredHeight of a text, the value just returns -1

I have a prefab that has a text component, a content size fitter, and a layout element. I instantiate the prefab and then fill the text field with some text. Then, I need to get the height of this text field, so I can set the size correctly. Apparently the way to do this is with the preferredHeight field. However, this isn’t working.

If I have the LayoutElement’s preferredHeight checkbox checked, then this preferredHeight value never updates as I fill in more text. It just stays at whatever value I give it in the prefab.

If I have the preferredHeight checkbox unchecked, then this value always returns -1 when I access it in code.

The only way that I can seem to make this work is to check the preferredHeight checkbox in the editor, after I have filled up the textfield. Then, it correctly shows the height. However, I can’t find another way to “check” this box programatically, or have it recalculate.

How do I do this?

@sglindme

Hi, I’ve no idea what your setup looks like, which gameObject has which component, and what the hierarchy looks like, but have you tried just using rect of your objects rectTransform?

Vector2 rectSize = rtra.rect.size;

EDIT: not sure if it will work in your case, but you can get width, height and size and other stuff from rect.

@eses

This didn’t work.

There is just one gameObject. This has a text component, a layout element, and a contentsizefitter. This is on a canvas, but other than that there is no heirarchy.

@sglindme

well why not post an image your layout?