- Home /
Unity Check if gameobject is clicked
This is a rather simple problem, but I can't fix it, I've looked for several answers for this but I can't get it to work.
I have a gameobject which is a raw image, what I want is that when I click on this image another image appears, I can already get it to work on keyboard, but I need with mouse as well, the somewhat interesting bit is that script tied to this gameobject just holds a boolean data that is sent to other scripts, those make the image appear, something like this
public bool touched = false;
void onMouseDown(){
touched=true;
}
That is everything I need it to do, so that when I clicked the object, the variable changes, then the rest take care of it, but I just can't get it to work.
I've looked for onMouseDown methods and all sorts of stuff, and it either doesn't work at all or works regardless of where I click, be it the button or not.
public bool touched = false;
void Update()
{
OnMouseOver();
}
void OnMouseOver()
{
if (Input.GetMouseButtonDown(0))
{
touched = true;
}
}
That is my code now, it works, but it doesn't matter where I click, rather than just the gameobject, from the other solutions I've found I can't get anything to work.
I'm working on Unity 3D, and added a box collider to my gameobject, still, no luck.
What am I missing?
You don't need to put On$$anonymous$$ouseOver() in the update script, because that is calling it all the time ins$$anonymous$$d of just when the mouse is hovering over.
Answer by Prastiwar · Dec 18, 2017 at 11:10 AM
So you have UI element, you can use button component in it or look at event trigger component. There is OnPointerDown method.
You can also do this via script, there you have an example: https://docs.unity3d.com/ScriptReference/UI.Selectable.OnPointerDown.html
Your answer
![](https://koobas.hobune.stream/wayback/20220612144755im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Convert Touch input to Mouse input C#? 1 Answer
Multiple Cars not working 1 Answer
OnMouseDown is checked when build for Android 2 Answers
Prime 31 Touch Kit detecting if touch hit gui element 1 Answer