OnMouseEnter bug ?

Hello,

I’m trying to create a script that allows me to click on an object (Money), increase a value (money), then delete the object.

I’ve got it to work in a way, but the script works only if I click into “Scene” view then click on the object in “Game” view. I would have to repeat that process if the script were to work again.

I’m not sure if it’s just a strange bug or if it’s my code, so I pasted my script below.

using UnityEngine;
using System.Collections;

public class money_collect : MonoBehaviour {

	public GameObject Player;
	public money_amount Script;
	
	void Start () {

		Player = GameObject.Find("Player");
		Script = Player.GetComponent <money_amount>(); 
	}

	void OnMouseEnter () {

		if (Input.GetMouseButtonDown (0)) {

			Script.money += 1;
			Destroy (this.gameObject);
		}
	}
}

OnMouseEnter is an event that fires once every time the mouse cursor enters the object area.

That means the only way your code will fire is if the mouse button is down at the exact time the cursor enters the object area.

Since the mouse is not tracked when the game view is not in focus, losing focus by clicking elsewhere and then clicking on your object causes the mouse to suddenly enter the object area at the exact same time as the mouse is pressed down. This runs your code.

I think the problem you’re coming across is that your mouse position doesn’t reflect in your game properly. The difference is your scene view will pick up the mouse’s SCREEN position and not it’s WORLD position. The world position is where you game actually exists.

The difference:

Mouse Position by screen would be a location in pixels. (x, y) could be anywhere on the screen. On a 1200x800 resolution, bottom left corner would be (0,0), top right (1200, 800), top left (800, 0), bottom right (0, 1200).

Mouse Position by world would be a location in world space, anywhere from (0, 0) <–bottom left, to (1, 1) ← top right.

In order to convert that, you can use many tools provided by unity to convert the mouse position.

void Update ()
{
  //This should make your mouse respond correctly in world space.
  Vector3 mouseCoords = Camera.main.ScreenToWorldPoint(Input.MousePosition);
}

Not sure if this is what you need, but there are plenty of other ways to do this. Attach the script to your camera.