Create a custom on-screen control
Derive a class from the on-screen control base class to report input from your own UI elements as a device control.
The built-in On-Screen Button and On-Screen Stick components cover buttons and sticks. For other UI elements, such as a slider or a dial, derive your own class from OnScreenControl. Your class sends values to the control in its control path, as if they came from a device.
Create the control class
To create a custom on-screen control class:
- Create a MonoBehaviour script, and change its base class to
OnScreenControl. - To receive presses and releases on the UI element, implement the
IPointerDownHandlerandIPointerUpHandlerinterfaces from theUnityEngine.EventSystemsnamespace. - Add a serialized
stringfield for the control path, and override thecontrolPathInternalproperty to return it.OnScreenControlreads this property to find the control to send values to. - To limit the Control Path picker in the Inspector window to one type of control, add the
[InputControl]attribute to the field. For example,[InputControl(layout = "Button")]. - In your event handlers, call
SendValueToControlto send a value to the control.
The following example recreates the built-in On-Screen Button with the minimum code. When the user presses the UI element, the button reports a value of 1, and when the user releases it, the button reports 0:
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem.Layouts;
using UnityEngine.InputSystem.OnScreen;
// Reports button input when the user presses and releases this UI element.
[AddComponentMenu("Input/My On-Screen Button")]
public class MyOnScreenButton : OnScreenControl, IPointerDownHandler, IPointerUpHandler
{
// The control that this on-screen button reports input as.
// The InputControl attribute limits the Control Path picker in the Inspector to buttons.
[InputControl(layout = "Button")]
[SerializeField]
private string m_ControlPath;
// OnScreenControl reads this property to find the control to send values to.
protected override string controlPathInternal
{
get => m_ControlPath;
set => m_ControlPath = value;
}
// Called when the user presses the UI element.
public void OnPointerDown(PointerEventData data)
{
SendValueToControl(1.0f);
}
// Called when the user releases the UI element.
public void OnPointerUp(PointerEventData data)
{
SendValueToControl(0.0f);
}
}
Use the custom control
To use the custom control in your scene:
- From the main menu, select GameObject > UI > Image. Unity adds a Canvas and an EventSystem if the scene doesn't have them.
- Add your custom component to the GameObject.
- In the Inspector window, set Control Path to the control that the on-screen control reports as input, such as Button South [Gamepad].
- Make sure the EventSystem has an Input System UI Input Module.
Any action bound to the control in Control Path now responds when the user presses the UI element.