Search Unity

  1. We are migrating the Unity Forums to Unity Discussions by the end of July. Read our announcement for more information and let us know if you have any questions.
    Dismiss Notice
  2. Dismiss Notice

Question Is mouse down and on?

Discussion in 'Scripting' started by Topfall, May 10, 2024.

  1. Topfall

    Topfall

    Joined:
    Dec 31, 2020
    Posts:
    15
    Is there an easy way to detect if the mouse is both holding down (like with void update) and touching a sprite? I can't find a way to mix them.
     
  2. Slaghton

    Slaghton

    Joined:
    Sep 9, 2013
    Posts:
    145
    Can you assign those sprites to a layer, then combine a layer detection with a mousebuttondown?

    I do something like this for my inventory sprites on screen (excuse the formating, did a sloppy job of copying and pasting). This is also using the old input system I believe. I assume this could be made to work with getkeydown/getbuttondown.

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using UnityEngine.UI;
    4. using UnityEngine.EventSystems;
    5. using System.Collections.Generic;
    6.  
    7. void Update()
    8. {
    9.  
    10. if (Input.GetKeyDown(KeyCode.Mouse0))  //This is just for a single press
    11. {
    12.  
    13. //Set up the new Pointer Event
    14. m_PointerEventData = new PointerEventData(m_EventSystem);
    15.  
    16. //Set the Pointer Event Position to that of the mouse position
    17. m_PointerEventData.position = Input.mousePosition;
    18.  
    19. //Create a list of Raycast Results
    20. List<RaycastResult> results = new List<RaycastResult>();
    21.  
    22. //Raycast using the Graphics Raycaster and mouse click position
    23. m_Raycaster.Raycast(m_PointerEventData, results);
    24.  
    25.  //For every result returned, output the name of the GameObject on the Canvas hit by the Ray
    26.      foreach (RaycastResult result in results)
    27.      {
    28.                if (result.gameObject.layer == 25)
    29.                {
    30.                     //This is where you'll put your logic code
    31.                 }
    32.           }
    33. }
    34. }
    Ah, guess zulo3d's approach may be simpler haha..
     
    Last edited: May 11, 2024
  3. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    1,118