Hi,
I am setting the text of a Text component at runtime. It has “Best Fit” enabled with minimum and maximum font size values. When I input text in the editor, Best Fit works fine. However, when I set the text at runtime, Best Fit doesn’t work — the text retains the same size as before.
Hi Ashok, this kind of issue often occurs because the text component’s best fit logic isn’t re-triggered when you update the text property at runtime. In Needle Engine the text layout is usually calculated during initialization, so setting the text dynamically won’t automatically re-run the best fit algorithm.
A common workaround is to manually force the text layout to update after changing the text. For example, after setting the text you can call the component’s layout update method (such as onParentRectTransformChanged) to force a recalculation of the best fit sizing. For example:
import { Behaviour, serializable, Text } from “@needle-tools/engine”;
export class UpdateText extends Behaviour {
@serializable(Text)
text?: Text;
onEnable() {
this.updateText();
}
updateText() {
if (this.text) {
// set your runtime text
this.text.text = “New runtime text with best fit enabled”;
// manually trigger a layout update to recalc best fit
this.text.onParentRectTransformChanged();
}
}
}
This call should prompt the text mesh to recalculate its size based on the current container dimensions and your minimum/maximum font settings. If the issue persists, please verify that your Best Fit settings are correct (for example, check the min and max font size values) and that you’re using the latest version of Needle Engine.
If you continue having trouble, try creating a minimal reproducible example on Needle-engine - Vite Template (duplicated) - StackBlitz and consider reporting the behavior to the Needle team for further diagnosis.
Hope this helps!
4 replies left
thread_qsdYSnyvaEG4RKnwJACLz82X
Reply to this post directly if you need further help (bottom right button)
Tried the bot suggestion as well as changing the enabled property but had no luck.
for (let i = 0; i < texts.length; i++) {
const currentText:Text = texts[i];
currentText.text = flagText;
//currentText.enabled = false;
///currentText.enabled = true;
currentText.onParentRectTransformChanged();
}
Console logging the text component shows that best fit is not enabled even though it enabled in the editor.
Hi, and thanks for the report – that’s strange. As a workaround, can you try enabling it via script?
We’re using three-mesh-ui under the hood, here’s how bestFit should look: three-mesh-ui | examples
I tried to do that, but the text here doesn’t have the bestfit property. Is there any other way to do this? The text I’m referring to here is from “@needle-tools/engine”.