Why is my application pausing when starting on Mac through Steam?

When our game is run on Mac through the Steam client, it appears that the window immediately loses focus after creation, and, if it’s not running fullscreen, is sent behind all other windows on the desktop. The player then has to cmd-tab to the game if it’s windowed, or click on it if it’s fullscreen, before the game registers any interaction.

The following events are coming through before the first update:

OnApplicationPause(False)
OnApplicationFocus(True)
OnApplicationPause(True)

Oddly there’s no OnApplicationFocus(False). If the game isn’t set to “Run in Background”, then we get just one call to Update() until the player manually restores focus to the app.

This only happens when running through Steam—running a build normally is fine. The current build uses Unity 4.6.6, but the same issue also hit us with 4.5 and 5.

Has anybody experienced similar behaviour? Is there any way to manually restore focus to a Unity app? I was thinking about writing an Objective C++ plugin to call the appropriate Cocoa API to restore focus, but that seems a little overkill.

Thanks!

Peter

Update: See almo’s answer. It’s a clean solution while this is just a workaround.


I ended up with the following solution, not elegant either but doesn’t require compiling and bundling a native extension.

Instead, I created a shell script and put it in the game’s executable place. The shell script opens the actual game and then tries to focus it, trying a given number of times and checking if the game has focus.

To use, rename the game’s executable in Game.app/Contents/MacOS to UnityPlayer, save the script below with the executable’s original name and make it executable using chmod +x path… in the terminal.

#!/bin/sh

sleepinterval=0.1
tries=10

cd "$(dirname "$0")"
appPath="$(pwd)/../.."

./UnityPlayer&

sleep "$sleepinterval"

script="POSIX file \"$appPath\" as alias equals path to frontmost application"
while [[ "$(osascript -e "$script")" = "false" ]] && [ "$tries" -gt "0" ]; do
	let "tries-=1"
	open "$(pwd)/../.."
	sleep "$sleepinterval"
done

Got it.

In your launch options, Steam’s default is:

Cognizer.app/Contents/MacOS/Cognizer

Don’t do that. Just put

Cognizer.app