I have a custom UI element that acts like a Scroll View. In the unity emulator I can drag the element up and down and it scrolls through a list of child elements. I want the list to have an initial scroll when the scene starts to show that it can be scrolled. Using the below script I tried to get this auto-scrolling effect by simulating drag event on the UI element as if I was scrolling it myself. Instead, it immediately shifts what appears to be a bit downward, then stops. I can’t seem to find the issue.
public class AutoScroller : MonoBehaviour
{
public RectTransform targetRectTransform; // The UI element (RectTransform) to simulate touch and drag on
public float dragDistance = 200f; // Distance to simulate drag (in pixels)
public float dragDuration = 1.0f; // Duration of the simulated drag (in seconds)
void Start()
{
// Simulate touch and drag on the target UI element
StartCoroutine(SimulateTouchAndDrag());
}
IEnumerator SimulateTouchAndDrag()
{
// Create a new PointerEventData
PointerEventData pointerEventData = new PointerEventData(EventSystem.current);
// Set the pointer event data position to the center of the target UI element
pointerEventData.position = targetRectTransform.position;
// Simulate a pointer down (touch) event
ExecuteEvents.Execute(targetRectTransform.gameObject, pointerEventData, ExecuteEvents.pointerDownHandler);
// Calculate drag start and end positions
Vector2 dragStartPosition = pointerEventData.position;
Vector2 dragEndPosition = new Vector2(dragStartPosition.x, dragStartPosition.y + dragDistance);
// Simulate drag movement
float elapsedTime = 0f;
while (elapsedTime < dragDuration)
{
float t = elapsedTime / dragDuration;
Vector2 currentPosition = Vector2.Lerp(dragStartPosition, dragEndPosition, t);
// Update pointer event data position
pointerEventData.position = currentPosition;
// Simulate drag handler on the target UI element
ExecuteEvents.Execute(targetRectTransform.gameObject, pointerEventData, ExecuteEvents.dragHandler);
elapsedTime += Time.deltaTime;
yield return null;
}
// Simulate a pointer up (release) event
ExecuteEvents.Execute(targetRectTransform.gameObject, pointerEventData, ExecuteEvents.pointerUpHandler);
}
}