color change and stay OnMouseOver

here’s the script:

var initialColor : Color;

function Start()
{
	initialColor = renderer.material.color;
}

function OnMouseEnter()
{
	renderer.material.color = Color.red;
}


function OnMouseExit()
{
	yield WaitForSeconds (0.3);
	renderer.material.color = initialColor;
}

The problem is, whenever i move my cursor over and stay on the object, color keeps blinking. I found out that OnMouseExit keeps kicking in even though my cursor is still staying on the object and make color constantly changing back and forth.

how can i fix and make object red for as long as my cursor still on it? preferably in javascript, thanks.

edit: i also tried OnMouseEnter but doesn’t work as i expected. it turned red then quickly back to initial color

Here’s a question with the same problem: OnMouseNotOver instead of OnMouseExit? - Questions & Answers - Unity Discussions.

You could do the same thing and check with OnMouseOver(). Or you could use constant Raycasting (expensive). I would probably use a class boolean for whether the mouse is inside the dot or not (set to true in OnMouseEnter() and check in Update() if Input.mousePosition has changed).

Edit: Try adding this.

function OnMouseOver() {
    renderer.material.color = Color.red;
}

Edit: Here’s a cheat that should work.

function OnMouseExit() {
    var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    var hit : RaycastHit;
    if(Raycast(ray, hit)) {
        if(hit.collider.gameObject == this.gameObject) {
            renderer.material.color = initialColor;
        }
    }
}