Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 11 Next capture
2021 2022 2023
2 captures
11 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
9
Question by John-Gray · Jul 22, 2015 at 04:38 PM · uimouseclick

Unity UI - Mouse Clicks Clearing Selected Object in Eventsystem

Hi,

I was wondering if anyone knows of a method to prevent mouse clicks deselecting objects in a scene when the click doesnt hit a UI element.

When I select a UI element and then click into the empty space next to it, the currently selected object becomes deselected.

Any advice on how to prevent this would be appreciated.

Cheers,

John

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image FerrenReve · Aug 23, 2015 at 04:35 PM 0
Share

Similar problem here, I want to navigate through the UI by only using the keyboard. However, because the mouse click is being detected (mouse is hidden and locked) the first selected object (button) becomes unselected and it results in me not being able to navigate niether with mouse nor keyboard.

4 Replies

· Add your reply
  • Sort: 
avatar image
22

Answer by IsaiahKelly · Feb 19, 2016 at 03:36 PM

You need to create your own custom Input Module to change this behavior.

  1. Create a new C# script and name it "MyInputModule".

  2. Copy & paste the StandaloneInputModule source code into this new script and replace all occurrences of "StandaloneInputModule" with "MyInputModule" in the newly copied code.

  3. To stop mouse clicks from deselecting objects, just delete or comment-out line 322 in the new script: DeselectIfSelectionChanged(currentOverGo, pointerEvent);

  4. Or to disable pointer input completely, just delete or comment-out line 179 in the new script: ProcessMouseEvent();

  5. Finally, remove the StandaloneInputModule script attached to the EventSystem object and replace it with your new MyInputModule script to use it.

@FerrenReve


myinputmodule.zip (3.2 kB)
Comment
Add comment · Show 7 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image noise256 · Apr 08, 2016 at 08:07 AM 1
Share

Thanks, this worked great.

In my case I still wanted objects to be deselected if there was a left click on nothing so I changed line 322 to:

                 if (data.buttonData.button == PointerEventData.InputButton.Left && !EventSystem.current.IsPointerOverGameObject()) {
                     DeselectIfSelectionChanged(currentOverGo, pointerEvent);
                 }

avatar image hansadler · May 28, 2017 at 12:06 AM 0
Share

Thanks for posting this, it worked great for me. However (@Unity) It's really annoying that there's no way to accomplish this without replacing the StandaloneInput$$anonymous$$odule.

avatar image k76 · Sep 10, 2017 at 11:10 AM 0
Share

If any of you are lucky enough to be using Rewired, and you want to disable mouse clicks completely, you can use the RewiredStandaloneInput$$anonymous$$odule. It has a "Allow $$anonymous$$ouse Input" checkbox that can be turned off. Just make sure that if you use this, you need to remove/disable any regular StandaloneInput$$anonymous$$odule components that happen to be in the scene.

avatar image astracat111 k76 · Feb 21, 2019 at 06:57 PM 0
Share

It's more so about just stopping the deselecting than allowing input. I can't believe we're all the way over on 2018.6 and there's still no way to do it.

avatar image armaan8014 · May 22, 2020 at 08:24 AM 0
Share

Thank you!!

avatar image Rugbug_Redfern · Sep 17, 2020 at 11:44 PM 0
Share

The link to the Unity UI source code is no longer available, and the .zip download doesn't work. If anyone has the code, please tell me.

EDIT: I think I found it https://pastebin.com/$$anonymous$$LEHvTVN ANOTHER EDIT: This is just supported with the new input system now. Scroll down to see more details in my answer.

Show more comments
avatar image
3

Answer by Rugbug_Redfern · Sep 18, 2020 at 01:05 AM

With the new Input System, you can just uncheck this box: alt text


deselect-on-background-click.png (50.9 kB)
Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image koZis · Sep 15, 2021 at 09:28 AM 0
Share

Perfect solution. For those who have the same problem and needs to fix it and use old EventSystems, there is an article which describes how to configure project: https://gamedevbeginner.com/input-in-unity-made-easy-complete-guide-to-the-new-system/

avatar image Ldwork_GameDev · Oct 31, 2021 at 09:19 AM 0
Share

Thank you so much. This is exactly what im looking for

avatar image
1

Answer by cjdev · Aug 23, 2015 at 07:24 PM

You could try using SetSelectedGameObject in the EventSystem to manually set the button as selected when the mouse is clicked like this:

 using UnityEngine.EventSystems;


 GameObject currentButton;
 EventSystem eventSystem;

 void Start ()
 {
     eventSystem = GameObject.Find("EventSystem").GetComponent<EventSystem>();

     GameObject buttonObj = GameObject.Find("Button");
     buttonObj.GetComponent<Button>().onClick.AddListener(() => { currentButton = buttonObj; });
 }

 void Update()
 {
     if (Input.GetMouseButtonDown(0))
         eventSystem.SetSelectedGameObject(currentButton);
 }
Comment
Add comment · Show 9 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image FerrenReve · Aug 23, 2015 at 09:00 PM 0
Share

Hi, I have tried out the script and I am getting this error. http://prntscr.com/8820ep

avatar image cjdev · Aug 23, 2015 at 09:10 PM 0
Share

Sorry the using UnityEngine.EventSystems; goes above the class name, I just didn't want to include the whole class to make the answer shorter.

avatar image FerrenReve · Aug 23, 2015 at 09:18 PM 0
Share

I have added the class name however, now a new error poped up. http://prntscr.com/882vi5

Sorry, I am not very good with program$$anonymous$$g and big thanks for helping out.

avatar image cjdev · Aug 23, 2015 at 10:13 PM 0
Share

Oops, you'll also need using UnityEngine.UI; If you like the interface I'd recommend using Visual Studio, it has a feature where you can right click and resolve to automatically put the using statement up top. I sometimes take that for granted.

avatar image FerrenReve · Aug 23, 2015 at 10:27 PM 0
Share

For some reason the button still becomes unhighlighted when i left click. Is there a way to completely remove mouse functionality from the game and block any mouse related input?

I think first selected is only relevant when the scene is loaded and after that it doesn't matter what happens with it it will not re highlight that button or effect the scene in any way.

Show more comments
avatar image
-1

Answer by astracat111 · Feb 21, 2019 at 06:59 PM

You can use a low level mouse hook like so. This is not global (do NOT use a global hook for a video game). This is only if you're completely and utterly not going to use the mouse or touch screen in your entire game. Just create an instace of this object and do myMouse.EnableClicks() or myMouse.DisableClicks().

 public class Mouse
 {
  
     #if UNITY_STANDALONE_WIN
     
     public WindowsLowLevelHook windowsLowLevelHook = new WindowsLowLevelHook();
     
     public void DisableClicks()
     {
         windowsLowLevelHook.Enable();
     }
     public void EnableClicks()
     {
         windowsLowLevelHook.Disable();
     }

     public class WindowsLowLevelHook
     {
         public bool enabled = false;

         public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
         public HookProc hookProc;
         
         public delegate void MouseHookCallback(MOUSEHOOKSTRUCT mouseHookStruct);
         
         #region Events
         public event MouseHookCallback LeftButtonDown;
         public event MouseHookCallback LeftButtonUp;
         public event MouseHookCallback RightButtonDown;
         public event MouseHookCallback RightButtonUp;
         public event MouseHookCallback MouseMove;
         public event MouseHookCallback MouseWheel;
         public event MouseHookCallback DoubleClick;
         public event MouseHookCallback MiddleButtonDown;
         public event MouseHookCallback MiddleButtonUp;
         #endregion
         
         public IntPtr hookID = IntPtr.Zero;
         public void Enable()
         {
             hookProc = MouseProc;
             hookID = SetHook(hookProc);
             enabled             = true;
         }
         public void Disable()
         {
             if (hookID == IntPtr.Zero)
                 return;

             UnhookWindowsHookEx(hookID);
             hookID                  = IntPtr.Zero;
             enabled                 = false;
         }
         ~WindowsLowLevelHook()
         {
             Enable();
         }

         private IntPtr SetHook(HookProc hookProc)
         {
             using (ProcessModule module = Process.GetCurrentProcess().MainModule)
                 return SetWindowsHookEx(WH_MOUSE, hookProc, GetModuleHandle(module.ModuleName), GetCurrentThreadId());
         }

         private IntPtr MouseProc(int nCode, IntPtr wParam, IntPtr lParam)
         {
             MOUSEHOOKSTRUCT lParamStruct = (MOUSEHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MOUSEHOOKSTRUCT));
             
             if (nCode >= 0)
             {

                 if (MouseMessages.WM_LBUTTONDOWN == (MouseMessages)wParam)
                 {
                     return (IntPtr)1;
                 }


             }
             return CallNextHookEx(hookID, nCode, wParam, lParam);
         }

         #region WinAPI
         private const int WH_MOUSE = 7;

         private enum MouseMessages
         {
             WM_LBUTTONDOWN = 0x0201,
             WM_LBUTTONUP = 0x0202,
             WM_MOUSEMOVE = 0x0200,
             WM_MOUSEWHEEL = 0x020A,
             WM_RBUTTONDOWN = 0x0204,
             WM_RBUTTONUP = 0x0205,
             WM_LBUTTONDBLCLK = 0x0203,
             WM_MBUTTONDOWN = 0x0207,
             WM_MBUTTONUP = 0x0208
         }

         private Int32 GetWindowThreadProcessID(IntPtr hwnd)
         {
             Int32 pid = 1;
             GetWindowThreadProcessId(hwnd, out pid);
             return pid;
         }

         [StructLayout(LayoutKind.Sequential)]
         public struct POINT
         {
             public int x;
             public int y;
         }
         
         [StructLayout(LayoutKind.Sequential)]
         public struct MOUSEHOOKSTRUCT
         {
             public POINT pt;
             public IntPtr hwnd;
             public uint wHitTestCode;
             public IntPtr dwExtraInfo;
         }
         

         [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
         private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, Int32 dwThreadId);

         [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
         [return: MarshalAs(UnmanagedType.Bool)]
         public static extern bool UnhookWindowsHookEx(IntPtr hhk);

         [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
         private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

         [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
         private static extern IntPtr GetModuleHandle(string lpModuleName);

         [DllImport("kernel32.dll")]
         private static extern Int32 GetCurrentThreadId();

         #endregion
     }


     #endif

 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

31 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Click Goes Everywhere 0 Answers

Native resolution fullscreen breaks UI clicks 0 Answers

How do i disable my buttons while dragging ScrollRect? 0 Answers

How do you check if the object that you want to destroy with a click is the right object? 1 Answer

My inventory opens and closes on left mouse click when i don't want it to. 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges