teaching machines

Colliding with and mutating text in Unity

October 11, 2012 by . Filed under public, unity.

Problem: I want, in the Unity game engine, to shoot projectiles at text and decrement the number the text is displaying.

Solution: Add a 3-D text game object. Add colliders to projectiles and the text. The collider on the 3-D text will automatically size itself around the bounds of the text. Implement OnTriggerEnter and update the textMesh.text on the 3-D text game object.

Problem: Suppose the number starts off at 1,000,000. When it gets down to 1, all the leading white space will still cause a trigger event. That’s dumb.

Solution: The collider doesn’t resize when the text changes; we have to do that manually.

Problem: I don’t know what numbers to use when resizing the collider.

Solution: Yeah, me neither. There’s no way to query the extent of the text, as far as I can tell.

Problem: That’s not a solution.

Solution: You’re right. A workaround is to remove the collider from the 3-D text and add a new one on. It’ll be sized appropriately.

// decrement and update label
value = value - 1;
textMesh.text = "" + value;

// remove stalely-sized collider
Destroy(GetComponent<BoxCollider>());

// add freshly-sized collider
gameObject.AddComponent<BoxCollider>();

Problem: Hey, cool! Wait. It doesn’t work. I get this error: “Can’t add component ‘BoxCollider’ to <GAME-OBJECT-NAME> because such a component is already added to the game object!”

Solution: Yeah, that problem stinks too. Destroyed objects aren’t destroyed right away. Unity waits till the end of the frame to really destroy things, or something. So, when you try to AddComponent, the previously destroyed component is still sitting there. I don’t know a good fix, but I offer another workaround. After you destroy the collider, set an isStale flag to true. In Update, if we’re stale, add your component and set the flag to false.