Search Unity

How can I toogle a bool with OnMouseOver() ?

Discussion in 'Scripting' started by Snicky, Jul 4, 2015.

  1. Snicky

    Snicky

    Joined:
    Mar 5, 2015
    Posts:
    36
    In a 2D scene I have a Slider gameobject. I want to click and then drag it left to right. So I need some logic to set a bool to true when the mouse is hovering above, and false when its not.

    Code (CSharp):
    1. public bool mouseOverButton;
    2.  
    3. void OnMouseOver()
    4.     {
    5.         mouseOverButton = true;
    6.     }
    This will set my boolean to true when I hover over it.

    How do I make it false now when the Mouseposition is outside the Slider Collider?
    Also, I have 6 Sliders in total in my Scene. Do I have to worry about perfomance if I use many Instances of this script?
    Thanks in advance :D.
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    OnMouseExit.

    But I you are using a slider, better choices would be implementing the EventSystems interfaces for pointer enter and pointer exit.
     
    Snicky likes this.
  3. Snicky

    Snicky

    Joined:
    Mar 5, 2015
    Posts:
    36
    Thank you,

    it works with the OnMouseExit. I will look into the EventSystems later and try to implement it as I am not familiar with it.
     
  4. Snicky

    Snicky

    Joined:
    Mar 5, 2015
    Posts:
    36
    Code (CSharp):
    1. bool clicked;
    2.  
    3. void OnMouseOver()
    4.     {
    5.  
    6.         if (Input.GetMouseButtonDown (0)) {
    7.             clicked = true;
    8.         }
    9.  
    10.     }
    11.  
    12. void Update () {
    13.         if (Input.GetMouseButtonUp (0)) {
    14.             clicked = false;
    15.         }
    16.         if (clicked){
    17.             transform.position = slider;
    18.         }
    (Vector3 slider is translated with ScreenToWorldSpace and only x value gets updated to move left&right)

    This is my solution for now. It is weird code, but gets the job done. When I click on slider, it will follow my Mouse. With OnMouseExit i run into the problem that when i moved the mousepointer to fast or up and down it would stop moving and not feel like a slider.