I’m currently working on an inventory system in Unity and have encountered an issue with mouse hover detection. I’m using the following code to track the slot that the mouse is hovering over:
public static class MouseData
{
public static GameObject SlotHoveredOver;
}
public abstract class UserInterface : MonoBehaviour
{
public void OnExit(GameObject obj)
{
MouseData.SlotHoveredOver = null;
}
public void OnEnter(GameObject obj)
{
MouseData.SlotHoveredOver = obj;
}
}
public class DynamicInterface : UserInterface
{
public int X_START;
public int Y_START;
public int X_SPACE_BETWEEN_ITEM;
public int Y_SPACE_BETWEEN_ITEM;
public int NUMBER_OF_COLUMNS;
public GameObject inventoryPrefab;
public override void CreateSlots()
{
slotsOnInterface = new Dictionary<GameObject, InventorySlot>();
for (int i = 0; i < inventory.GetSlots.Length; i++)
{
var obj = Instantiate(inventoryPrefab, Vector3.zero, Quaternion.identity, transform);
obj.GetComponent().localPosition = GetPosition(i);
AddEvent(obj, EventTriggerType.PointerEnter, delegate { OnEnter(obj); });
AddEvent(obj, EventTriggerType.PointerExit, delegate { OnExit(obj); });
AddEvent(obj, EventTriggerType.BeginDrag, delegate { OnDragStart(obj); });
AddEvent(obj, EventTriggerType.EndDrag, delegate { OnDragEnd(obj); });
AddEvent(obj, EventTriggerType.Drag, delegate { OnDrag(obj); });
AddEvent(obj, EventTriggerType.PointerClick, delegate { OnPointerClick(obj); });
inventory.GetSlots*.slotDisplay = obj;*
slotsOnInterface.Add(obj, inventory.GetSlots*);*
}
}
}
The SlotHoveredOver is updated in the OnEnter and OnExit methods as the mouse enters and exits a slot. Despite this implementation, I’m occasionally experiencing issues with the correct detection of the hovered slot.
I have a gif of a screen recording to show the error. To explain the Gif, in the scene view you can make out a small green circle correctly tracking my mouse movement on the UI canvas. Also in my Scene view you will see a red outline in each slot that signifies the “hit box” of the slot to detect my mouse. In the game scene you can see my inventory slots change color to purple when they think they are being hovered over and red when I click them. You will see some slots turn purple even though my mouse is not hovered over them. So I think it has to do with something mucking up my OnEnter() since it is being called for the wrong slot at times.
GifURL: - Find & Share on GIPHY
_(Gif also attached)*
I think it could also be related to my ui canvas being much larger than my Main Camera. However, I do have the Canvas set to scale with Screen Size. It might be worth noting that the Canvas is also set to Screen Space Overlay.
Any help or suggestions is greatly appreciated!!