Is this a good way of getting the players device?

Of all ways to get a player’s device, is this an alright way to do it?

function playerModule.getPlayerDevice()
	if UserInputService.KeyboardEnabled and not UserInputService.TouchEnabled then
		return "pc"
	elseif UserInputService.TouchEnabled and not UserInputService.KeyboardEnabled then
		return "mobile"
	end 
end

The best practice is to write platform agnostic code; Don’t worry about what platform a player is on, instead focus on which input device types are currently being used.

For example, I might be playing on my PC (which has a Keyboard and Mouse connected), but I prefer to play using a Gamepad (PS5 or XBox controller) also connected to my PC.

Ideally, your input systems should be able to handle switching between input types mid session. Check out UserInputService.PreferredInput, UserInputService.LastInputTypeChanged, and the new Input Action System for more info on how to achieve this.

2 Likes

using the not is not needed as it there isn’t a way to have both enabled (I think)
but for the elseif, keyboardEnabled will never be true so you can remove that.
But East98 is right, PreferredInput is the best

A touchscreen laptop would likely have both TouchEnabled and MouseEnabled reading true. Or potentially a phone/tablet with a mouse connected.

1 Like

oh my god I completly forgot about these

You can use PreferredInput like I showed below but I used to do it like this with GamepadEnabled as well and it worked just as fine imo

instead of:

if UserInputService.KeyboardEnabled and not UserInputService.TouchEnabled then
	return "pc"

use

if UserInputService.PreferredInput == Enum.PreferredInput.KeyboardAndMouse and not UserInputService.PreferredInput == Enum.PreferredInput.Touch then
	return "pc"

You can also do the same with Enum.PreferredInput.Gamepad if Console is enabled in your Game Settings