- Home /
ScrollRect Gamepad support?
So currently the scrollrect only works with mouse scrollwheel and mouse drag. Is there actually a way to get it working with gamepad? Eg right analog or something? Looked at documentation, didnt see anything really useful
Answer by KurtGokhan · Jan 15, 2015 at 03:59 PM
You can implement a new class from Scrollrect and IMoveHandler. Also IPinterClickHandler so you can select the object on pointer click. Full code looks like this. You should attach this to your ui object which is going to be ScrollRect.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class MoveScrollRect : ScrollRect, IMoveHandler, IPointerClickHandler {
private const float speedMultiplier = 0.1f;
public float xSpeed = 0;
public float ySpeed = 0;
private float hPos, vPos;
void IMoveHandler.OnMove(AxisEventData e) {
xSpeed += e.moveVector.x * (Mathf.Abs(xSpeed) + 0.1f);
ySpeed += e.moveVector.y * (Mathf.Abs(ySpeed) + 0.1f);
}
void Update() {
hPos = horizontalNormalizedPosition + xSpeed * speedMultiplier;
vPos = verticalNormalizedPosition + ySpeed * speedMultiplier;
xSpeed = Mathf.Lerp(xSpeed, 0, 0.1f);
ySpeed = Mathf.Lerp(ySpeed, 0, 0.1f);
if(movementType == MovementType.Clamped) {
hPos = Mathf.Clamp01(hPos);
vPos = Mathf.Clamp01(vPos);
}
normalizedPosition = new Vector2(hPos, vPos);
}
public void OnPointerClick(PointerEventData e) {
EventSystem.current.SetSelectedGameObject(gameObject);
}
public override void OnBeginDrag(PointerEventData eventData) {
EventSystem.current.SetSelectedGameObject(gameObject);
base.OnBeginDrag(eventData);
}
}
I couldn't find an elegant way to update ScrollRect position. Also as you see I calculate the scrolling speed myself. It can be tweaked to work better. Anyways, if you improve the code, let me know.
cool so I'm assu$$anonymous$$g this will work for gamepad too? Also, while we are on the subject, is it possible to make it so if gamepad is plugged in, it will scroll to a certain point?
I have tested. It works with gamepad. You can set "normalizedPosition" field to scroll the ScrollRect. It should take a value between 0 and 1 if you want it to stay in frame. Input class has methods that tells if a gamepad is connected or not. You can use that to set the position and also select the rectangle when a joystick is connected.
I have a problem. The scrolling works fantastically thank you very much now my problem is, if I want to select a button which is further down I cant do that because I scroll to it and then my gamepad actually doesnt want to select any buttons