OnMouseDown() ignoring part of method
When OnMouseDown executes, it destroys the gameObject but doesn't execute either of the other statements.
using UnityEngine;
using UnityEngine.UI;
public class Apple : MonoBehaviour
{
public Image crosshair;
public Text tip;
void OnMouseOver()
{
crosshair.color = Color.red;
tip.text = "Apple";
}
void OnMouseExit()
{
crosshair.color = Color.white;
tip.text = "";
}
void OnMouseDown()
{
tip.text = "";
crosshair.color = Color.white;
Destroy(gameObject);
}
}
Answer by Techn0pug · Aug 13, 2019 at 01:55 AM
Fixed it. I guess OnMouseOver() was the last method that was called before the gameObject was destroyed.
Answer by Bunny83 · Aug 12, 2019 at 11:09 PM
You can be sure that if there's no exception thrown that the code is executed. If the result is not what you expect, then one or multiple of your initial assumptions are wrong. In your specific case you should make sure that you actually reference the correct "Image" and "Text" object in your variables. You can use a Debug.Log with a context object to figure out which objects are involved. Try adding those 3 statements to the beginning of your OnMouseDown method:
Debug.Log("OnMouseDown", gameObject);
Debug.Log("referenced tip object", tip.gameObject);
Debug.Log("referenced crosshair object", crosshair.gameObject);
Now when your method runs 3 log messages will be produced. When you click on one of the log messages in the console, Unity will ping / highlight the context object we passed along. That way you can see which objects are actually affected.
On$$anonymous$$ouseOver() and On$$anonymous$$ouseExit() work fine, so I think my references are okay. On$$anonymous$$ouseDown() is the problem.
Your answer
![](https://koobas.hobune.stream/wayback/20220612210544im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to trigger game pause with clicking object instead of keycode? 0 Answers
Disable mouse click on gameObject 1 Answer
On Off sound 0 Answers
On-click and trigger animation c# 1 Answer
about create plane by script 1 Answer