Search Unity

OnMouseOver/Exit doesn't work together to Hover

Discussion in 'Scripting' started by FreshCoder-731319, Aug 3, 2020.

  1. FreshCoder-731319

    FreshCoder-731319

    Joined:
    May 21, 2020
    Posts:
    17
    I am trying to accomplish a hover state for when a mouse enters and exits the GameObject.
    Only when the OnMouseExit is //commented out the function OnMouseOver() decides to work but the OnMouseExit will not. Both function will not work together.

    ....when the OnMouseOver() works the hover will not deactivate again. Which is why i am trying to use OnMouseExit()

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEditor.UI;
    5.  
    6. public class NewBehaviourScript : MonoBehaviour
    7. {
    8.     public GameObject selected;
    9.     public GameObject hover;
    10.  
    11.  
    12.     // Start is called before the first frame update
    13.     void Update()
    14.     {
    15.         if (Input.GetMouseButtonDown(0))
    16.         {
    17.             selected.SetActive(true);
    18.             hover.SetActive(true);
    19.  
    20.         }
    21.     }
    22.  
    23.     void OnMouseOver()
    24.     {
    25.         hover.SetActive(true);
    26.     }
    27.  
    28.     //     public void OnMouseExit()
    29.     //     {
    30.     //         hover.SetActive(false);
    31.     //     }
    32.  
    33.  
    34.  
    35.  
    36. }
    37.  
     

    Attached Files:

  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,911
    If you're using an event trigger, you shouldn't also be using Unity "Magic Methods" like OnMouseOver and OnMouseExit. https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseExit.html Those methods are for 3d objects with colliders. Make your own method names so they don't conflict with this separate concept in Unity.

    As for your specific issue, you have both methods set as callbacks for the "Pointer Enter" event. You need to click the "Add a new event type" button and add a Pointer Exit listener, and add OnMouseExit to that event. As it is right now Unity will call both methods on pointer enter.
     
    eisenpony likes this.