Simulating touch events in Play mode in Unity

This should have been easy, but it really wasn't. I wish the information was more prominently displayed in the Unity docs and tutorials.

How to do it

  • Go to Window, Analysis, Input Debug.
  • In the Options dropdown, check Simulate Touch Input From Mouse or Pen.
  • The Simulated Touchscreen will be added to the list of devices.
  • Run Play Mode. Mouse interactions will now trigger touch events.
No simulated touchscreen initially
Now mouse clicks and drags will simulate tap events

How I thought I should do it

As I was implementing unit tests for touch interactions, I stumbled upon https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/api/UnityEngine.InputSystem.EnhancedTouch.TouchSimulation.html. The class description states:

Adds a Touchscreen with input simulated from other types of Pointer devices (e.g. Mouse or Pen).

That's perfect! Now how to add this simulator? There's an static instance field and an AddPointer method that takes a Device. Let's try:

var mouse = InputSystem.GetDevice<Mouse>();
TouchSimulation.instance.AddPointer(mouse);

But the AddPointer method is protected.

I then called Debug.Log(TouchSimulation.instance.enabled) and it threw a null pointer exception. So the TouchSimulation is not even instantiated. Let's try the static Enable method.

TouchSimulation.Enable();
Debug.Log(TouchSimulation.instance);

This does instantiate TouchSimulation, but somehow it didn't seem to have any effect.

Now I wish the doc for this class explicitly stated how a user should enable the simulated touchscreen in the IDE.

Aftermath

Fast forward a few hours, I just stumbled upon https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/Touch.html#touch-simulation, that explains how to enable simulation programmatically. What I was missing is adding a Component in a GameObject in my Scene.