2D Game - OnMouseOver/Other Event Triggers not working?

I’m currently trying to make an onscreen button that when clicked will exit the current level. Simple enough. To start off, however, I decided created a game object that would print to the log when the mouse was over it. So I made this code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Explode : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
           
    }
    // Update is called once per frame
    void Update()
    {
           
    }
    void OnMouseOver()
    {
        //If your mouse hovers over the GameObject with the script attached, output this message
        Debug.Log("Mouse is over GameObject.");
    }

}

And then attached it to the game object like so:

Yet when I run the game and bring my mouse over the game object, nothing gets logged. When I tried the code with onMouseDown, it didn’t work either. What’s going on? Is this a layering issue?

This is what i googled on the issue:

Your code is fine. Make sure:

  • this script is attached to the object you’re trying to use

  • that the object has a collider

  • Your object is not obstructed (it is the closest thing to the mouse, the event only gets called on the first thing the mouse touches, use Debug.Log ("over: "+ name) if not sure )

  • it CAN NOT be a UI element (i.e. in the canvas with a rect transform)

also you are probably looking for OnMouseEnter or OnMouseDown as OnMouseOver gets called every frame.

Soooo, you probably need a collider2D

1 Like