Search Unity

Tip: use Event.current.delta to make text label scroll on touch devices

Discussion in 'Immediate Mode GUI (IMGUI)' started by clever, Feb 23, 2020.

  1. clever

    clever

    Joined:
    Oct 11, 2012
    Posts:
    39
    Hey colleagues, thought I would post a tip for those still using Unity's old GUI (which imho still has essential uses).

    I was trying to get a label scroll on mobile devices when the user swipes up/down. Instead of handling touch events separately, I simply used Event.current.delta in my GUI code since Unity records touch locations as if they are mouse pointer ones in Event. It's not perfect (and sometimes jittery) but since it's a feature for debugging in my app, i didn't mind. It could easily be couched in a Lerp or something to make it more professional. Anyways, thought I would share the code as I didn't find any info on this when I searched for it and others may have the same challenge.

    Here's a quick-n-dirty message box code:
    Code (CSharp):
    1. void MessageWindow(int windowID)
    2. {
    3. // for my needs I simply used GUILayout as in many of my GUI windows they change based on input.
    4. //So could'nt be bothered with precise Rects
    5.  
    6.         GUILayout.Space(5f);
    7.         GUILayout.BeginVertical();
    8.  
    9.         msg_scroll = GUILayout.BeginScrollView(msg_scroll);
    10.         GUILayout.Label(message);
    11.         GUILayout.EndScrollView();
    12.        
    13.     GUILayout.Space(10f);
    14.         GUILayout.FlexibleSpace();
    15.  
    16. // HERE is the code that interprets touch/swipe movement to make the label scroll vertically
    17. // To minimize jitter when user touches different locations
    18. // i ignore touch events that are too far apart using "Mathf.Abs(Event.current.delta.y) < 15f"
    19.         msg_scroll.y += Mathf.Abs(Event.current.delta.y) < 15f ? Event.current.delta.y : 0;
    20.        
    21.  
    22.         if (GUILayout.Button("Ok") || Event.current.keyCode == KeyCode.Return || Event.current.keyCode == KeyCode.KeypadEnter)
    23.         {
    24.             CloseWindow();
    25.     }
    26.        
    27.     GUILayout.EndVertical();
    28. }