| | 1 | | using System.Collections; |
| | 2 | | using UnityEngine; |
| | 3 | | using UnityEngine.UI; |
| | 4 | |
|
| | 5 | | /// <summary> |
| | 6 | | /// Let to set a dynamic sensitivity value depending on the height of the content container. |
| | 7 | | /// Call to RecalculateSensitivity() function to calculate and apply the new sensitivity value. |
| | 8 | | /// </summary> |
| | 9 | | public class DynamicScrollSensitivity : MonoBehaviour |
| | 10 | | { |
| | 11 | | [Tooltip("Scroll Rect component that will be modified.")] |
| | 12 | | public ScrollRect mainScrollRect; |
| | 13 | | [Tooltip("Min value for the calculated scroll sensitivity.")] |
| 192 | 14 | | public float minSensitivity = 5f; |
| | 15 | | [Tooltip("Max value for the calculated scroll sensitivity.")] |
| 192 | 16 | | public float maxSensitivity = 50f; |
| | 17 | | [Tooltip("Multiplier applied to the sensitivity value (sensitivityMultiplier = 1 for not applying).")] |
| 192 | 18 | | public float sensitivityMultiplier = 0.5f; |
| | 19 | | [Tooltip("True to recalculate each time the game object is enabled.")] |
| 192 | 20 | | public bool recalculateOnEnable = true; |
| | 21 | |
|
| | 22 | | private Coroutine recalculateCoroutine = null; |
| | 23 | |
|
| | 24 | | private void OnEnable() |
| | 25 | | { |
| 67 | 26 | | if (recalculateOnEnable) |
| 67 | 27 | | RecalculateSensitivity(); |
| 67 | 28 | | } |
| | 29 | |
|
| 126 | 30 | | private void OnDestroy() { KillCurrentCoroutine(); } |
| | 31 | |
|
| | 32 | | /// <summary> |
| | 33 | | /// Recalculate the scroll sensitivity value depending on the current height of the content container. |
| | 34 | | /// </summary> |
| | 35 | | public void RecalculateSensitivity() |
| | 36 | | { |
| 73 | 37 | | KillCurrentCoroutine(); |
| 73 | 38 | | recalculateCoroutine = CoroutineStarter.Start(RecalculateCoroutine()); |
| 73 | 39 | | } |
| | 40 | |
|
| | 41 | | private IEnumerator RecalculateCoroutine() |
| | 42 | | { |
| | 43 | | // We need to wait for a frame for having available the correct height of the contentContainer after the OnEnabl |
| 73 | 44 | | yield return null; |
| | 45 | |
|
| 16 | 46 | | if (mainScrollRect.content != null) |
| | 47 | | { |
| 16 | 48 | | float newSensitivity = (mainScrollRect.content.rect.height * minSensitivity / mainScrollRect.viewport.rect.h |
| 16 | 49 | | mainScrollRect.scrollSensitivity = Mathf.Clamp(newSensitivity, minSensitivity, maxSensitivity); |
| | 50 | | } |
| 16 | 51 | | } |
| | 52 | |
|
| | 53 | | private void KillCurrentCoroutine() |
| | 54 | | { |
| 136 | 55 | | if (recalculateCoroutine == null) |
| 63 | 56 | | return; |
| | 57 | |
|
| 73 | 58 | | CoroutineStarter.Stop(recalculateCoroutine); |
| 73 | 59 | | recalculateCoroutine = null; |
| 73 | 60 | | } |
| | 61 | | } |