I don’t understand why this isn’t working, I’ve a cube on the scene with a simple collider, in the OnMouseEnter a simple print(“hello”) for testing, but when I move the mouse over the 3d object the function isn’t called. Am I forgetting something? What the problem could possibly be?
6 Answers
6The object using OnMouseEnter must have a collider.
Check if yours does.
OnMouseEnter may not work if an other collider is occluding it. If this is the case, either prevent the other collider from occluding (maybe it can be disabled?), or do a manual check to see if the cursor is inside any object behind it:
bool hovered = false;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
foreach(RaycastHit hit in Physics.RaycastAll (ray))
{
if (hit.collider == collider)
{
hovered = true;
break;
}
}
If you have tried everything and it still doesn’t work, its because OnMouseEnter and such methods don’t support the NewInputSystem properly yet, so just go into your Player Settings and change the Active Input Handling to Both (the old and the new input systems) and it should start working.
if you don’t want to use any ray casting, you can do this :
var clicked = false;
function OnMouseDown(){
//click object multiple times to turn on or off.
//if mouse is being clicked else where, then noting should happen.
clicked = !clicked;
}
function Update(){
if (clicked == true){
//what will happen when this is true
}
}
just keep in mind-
1.The object needs a collider
2.This script needs to go on the object you want to be clicking
using UnityEngine;
public class Interactable : MonoBehaviour
{
[SerializeField] private Color _highlightedColor;
private Color _originalColor;
private Material _material;
void Start()
{
Renderer rend = GetComponent<Renderer>();
_material = new Material (rend.material);
rend.material = _material;
_originalColor = _material.color;
}
void OnMouseEnter()
{
_material.color = _highlightedColor;
}
void OnMouseExit()
{
_material.color = _originalColor;
}
}
You better create your own copy of the material so when you change it, other objects aren’t affected.
where u attached script (where u make function OnMouseEnter )on cube or not, if u attached on cube then it will work perfectly.
Here's a silly question: Is the script attached to the gameobject?
– CHPedersenYes it is, I really don't know what to do.
– sonic220http://unity3d.com/support/documentation/ScriptReference/MonoBehaviour.OnMouseEnter.html
– KacerAlready looked at it, seems like all is set up correctly, but it doesn't work
– sonic220do you have another collider blocking the collider you're trying to come into contact with?
– Kacer