SpriteFont: ignore unsupported characters?

I have a game where the user can type in their name for the high score table.
However the high scores are displayed with a SpriteFont. If the user types in characters that aren’t included in the .spritefont file (like emojis, etc.), the game crashes. I haven’t looked into it, but I assume it throws some sort of exception when it hits the unsupported character and gives up.

Is there a way to have it just ignore unsupported characters, instead of shitting the bed?

Cheers!

It’s been a while since I’ve looked, but I think a SpriteFont might tell you the character ranges it supports. You could probably scrub the input string when it’s given, or before you send it out to the renderer, stripping out any unsupported characters at that time.

I’m not sure if there’s any built-in way to have it just ignore these, just offering a suggestion :slight_smile:

1 Like

UTF-8 filter, saw someone mention it recently…

This is the way! When dealing with user input don’t remove the things you don’t want them to do. You should make everything forbidden :slight_smile: except the inputs you want users to be allowed to do.

1 Like

c# - Filter a String - Stack Overflow

1 Like

Ugh, I hate that it works this way… like a Japanese player puts kanji in his initials, and now the app is completely poisoned. It’ll crash every time the high score table is displayed!
I was hoping there was a flag, like
spriteFont.ShitTheBed = False;
and it would just work, and display a square for unrecognized characters like every other piece of software. I’m probably going to fork MonoGame, find where it throws that exception, and just NOT do that.

So annoying. This is the last thing to do on a really dumb project, and now that I’ve realized how bad this bug it, I can think of like 10 different places in 4 different apps that I’m going to have to go fix :frowning:

2 Likes

There is, you have to set the SpriteFont.DefaultCharacter in code or <DefaultCharacter>
inside your .spritefont description.
https://docs.monogame.net/api/Microsoft.Xna.Framework.Graphics.SpriteFont.html

5 Likes

I get around this by restricted the key presses accepted by the input field to alphanumeric characters and some control ones (shift, backspace, enter, delete etc). This works fine.

That will work too.

Another idea is to show an on-screen-keyboard with only latin characters when the user clicks on the input field.

1 Like

Thank you, this was the answer. I added to all my .spritefont files:
<DefaultCharacter>*</DefaultCharacter>

5 Likes

If you do a character that’s nor part of the supported characters. the spritefont.draw willl crash.

Lets say you only want characters from a-z but you type 0 (zero). it will crash.