Home > Blockchain >  How can i avoid spaming my Console with the OnMouseOver Function?
How can i avoid spaming my Console with the OnMouseOver Function?

Time:03-02

The code works, but is there a possibility that the onm ouseOver function does not spam the Console? I'm always open to suggestions for improvement Thx. :3

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

public class HoverButton : MonoBehaviour
{ 
    private bool Hovering = false;

    private void onm ouseOver() 
    {
        Hovering = true;
    }

    void Update()
    {
        Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        if(Hovering)
        {
            Collider2D HoveringButton = Physics2D.OverlapPoint(mousePos);

            if(HoveringButton)
            {
                Debug.Log("Hi");
            }
        }
    }
}

CodePudding user response:

is there a possibility that the onm ouseOver function does not spam the Console

Yes: Don't log something every frame => Add some condition checks that log only once.


Anyway, you rather want to use

private bool hovering;

private void onm ouseEnter() 
{
    hovering = true;
    Debug.Log("Hi");
}

private void onm ouseExit() 
{
    hovering = false;
}

otherwise the Hovering would never be reset to false.


The Physics2D.OverlapPoint seems quite redundant since if OnMouseEnter is called it already means that your current mouse position is overlapping this object's collider.

IF - for whatever reason - you then still need to do this anyway, you could simply store the current hit and compare like e.g.

private bool hovering;

private Collider2D currentHoveringButton;

private void Update()
{
    if(!hovering) return;

    var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

    var hoveringButton = Physics2D.OverlapPoint(mousePos);

    if(hoveringButton && hoveringButton != currentHoveringButton)
    {
        Debug.Log("Hi");
    }
    
    currentHoveringButton = hoveringButton;
}
  • Related