- Home /
OnMouseEnter when enabling a object
I have a game object with the following script for example:
public class ExampleClass : MonoBehaviour {
public Renderer rend;
void Start() {
rend = GetComponent<Renderer>();
}
void OnMouseEnter() {
rend.material.color = Color.red;
}
void OnMouseExit() {
rend.material.color = Color.white;
}
}
In other script I handle this game object disabling or enabling it. The problem is when I disable it and the mouse is away of the game object, if I enable it again and now the mouse is on the object, in this situation the OnMouseEnter event will never be called. It only will be called if I exit and enter again. How to solve that, I have to use OnMouseOver just to check this?
Answer by Dave-Carlile · Aug 03, 2015 at 04:22 PM
You might be able to handle with this with OnEnable. You'd have to check to see if the mouse is over the object and set the color accordingly. Not much different than just using MouseOver, but only runs once instead of each frame.
I thought about that, but how to know if the mouse is over on the object in OnEnable?
Answer by NeverHopeless · Aug 04, 2015 at 01:22 PM
Perhaps like this: (untested code to give you an idea, i assume it is 2D, if not you have to remove the 2D
elsewhere)
bool stateChanged = false;
void Update()
{
if(stateChanged) {
if(gameObject.isEnabled && Physics2D.OverlapPoint(cameraConvertedMousePos) != null)
{
// color.red
} else {
// color.white
}
stateChanged = false;
}
}
void OnEnable()
{
stateChanged = true;
}
void OnDisable()
{
stateChanged = true;
}
Hope it helps!
Your answer

Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Multiple GUI textures one script 2 Answers
[Solved]MouseEnter not working! 1 Answer