I’ve been loocking for this for a while, but all I’ve found was OnMouseOver() function. I don’t konow why but this doesnt work anymore.
Raycast doesnt wok either.
I need that when the mouse is over an object, image is showed instead of the normal cursor
Please help!
Be sure the objects you wish to detect have a Collider attached, and use a RayCast, or OnMouseOver.
You didn’t specify your language so I’ll give a JS and CS example.
JS Example of Raycast:
//Attach this script to your Main Camera, or an Empty GameObject.
#pragma strict
var ray : Ray;
var hit : RaycastHit;
function Update ()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, hit))
{
Debug.Log(hit.collider.name);
}
}
C# Example on Raycast:
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
Ray ray;
RaycastHit hit;
void Update()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit))
{
print (hit.collider.name);
}
}
}
JS Example on OnMouseOver():
//Attach this to each object that will need to be detected. This is why I prefer Raycast, becasue with Raycast, you only need one instance of the script.
#pragma strict
function OnMouseOver()
{
print(gameObject.name);
}
C# Example on OnMouseOver():
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
void OnMouseOver()
{
print (gameObject.name);
}
}
These links have everything that you need:
There are 3 options to solve this problem. All of them will trigger the MonoBehavior method OnMouseOver
. In my case the issue was trying to detect the mouse via trigger area.
- Use a collider (set to trigger false)
- Use a collider (set to trigger true). You will need to set your physics settings to force triggers to be detected by raycasts. This is generally not a good idea as every trigger in your game will now intercept raycasts
- Create a new layer called
Interactions
and set it to interact with nothing on the collision matrix. Create a collider and object as normal with the new layer. The important part here is that you have a script that emits an event on the object so other scripts can make use of the mouse events
In my case option 3 did the trick. I can now have invisible trigger detection areas without affecting any other system. It works for keyboard / mouse and could easily be extended to work with a gamepad. Option 1 and 2 both created a giant mess for me.