Focus lost when destroying TextField

I have a game I’m working on that was seemingly “soft-locking” whenever I switched from one level to the next. The only way I could get it to respond to any input again (specifically the keyboard) was by clicking on the screen.

After some testing, I think I’ve deducted that the game is losing focus. Reproduction of the issue more or less goes like this:

  1. I click on a TextField object

  2. I switch levels (which destroys the TextField)

  3. The game usually becomes unresponsive until I click on any part of the game screen

Its almost as if the TextField was being “focused,” and when it was destroyed the game didn’t know know where to redirect said focus. The object currently has “selectable=false” so that doesn’t seem to be the issue. Any idea what’s going on?

Running OpenFL 3.6.1, by the way.

Well, that was quick.

I dug a bit deeper into the inheritance tree and turned “mouseEnabled” from InteractiveObject to false as well. This seems to have cleared up the issue. Always great when you finally ask for help then find a solution ten minutes later, eh?

I’d still be interested to know why the game was losing focus though, as this may not always be a viable solution depending on the circumstances.

This is a known issue in Flash. Use this to solve it:

#if flash
	if(stage.focus != stage) {
		var obj:DisplayObject = stage.focus;
		while(obj != stage) {
			if(obj == null || !obj.visible) {
				stage.focus = stage;
			} else {
				obj = obj.parent;

Run this every frame, and you won’t have to worry about this problem again.

The cause is that Flash sends keyboard events to stage.focus, and then the events “bubble up” from there. Since you use the stage (or the main class) to listen for keyboard events, you won’t receive them if stage.focus gets removed from the stage.

I’m not 100% sure since I wrote this code snippet years ago, but it seems that invisible objects also stop events from “bubbling up.”

Note: if you add your keyboard event listeners to your Main class rather than the stage, you’ll want to replace the references to stage with references to this. (Except don’t replace the references to stage.focus.)

Thanks for the workaround and the explanation. :slight_smile: