How to get width of a text label?

I’m creating a prototype where a hero sprite needs to answer questions by colliding with one of two text labels (the one he collides with is his answer). A problem I’m facing is the answer will have different width which will affect the box collider (e.g. if answer is “妈妈” then the length could be120px, while if the answer is “爸爸妈妈” then the width could 240px).

Is there a way to determine the width of a text label after the string is updated? For instance, I would like to dynamically update the box collider according to the red lines.

You can try

label.string = ...;
label.updateRenderData(true)
const size = label.node.getComponent(UITransform).contentSize;
2 Likes

there is 2.x version of Cocos Creator, so there is no UITransform.

In Creator 2.x, you can try

Demo:
NewProject_2411.zip (234.0 KB)

In Creator 3.x, you can try

label.string = ...;
label.updateRenderData(true)
const size = label.node.getComponent(UITransform).contentSize;

Thank you!