So i have this code Change prefab action - Unity Engine - Unity Discussions … and i have GameObject – and than 4 prefabs in therem but problem is that i cant manage OnClick that call ClickedObject(); … i put fuction:
if (Input.GetMouseButtonDown (0))
{
ClickedObject ();
}
but problem is that it works EVERYWHERE i click on game screen . but i want that only work on that particularly GameObject, how i can manage that in this code, please help.
Like @romatallinn suggested OnMouseDown. To do this you’ll need to put some kind of collider on your object (box , sphere , whatever) or it will work if its UI Element.
Hello thank you for answers but where i put that … because my ClickedObject(); should be inside Update(); … i put on bottom OnMouseDown method and call Update (code bellow) … cause i can put in Update method void OnMouseDown… so i did this …
Calling Update() from other function is not good practise. Please try to avoid it.
You don’t need RayCastHit2D at all if you use OnMouseDown(). Just note that the script with OnMouseDown must be a component added to same object that has the collider.
Update is used to make something happen every frame
OnMouseDown is to make something happen whenever the mouse is clicked on it.
Which of the two above should your code do for ClickedObject()?
Just to note: Using RayCastHit2D to check if the point clicked hit your object, is EXACTLY what Unity does already behind the scenes. It then calls OnMouseDown if the RayCastHit actually hit any object that has an OnMouseDown
Great that it works. Also note, the comments by myself and @Zaflis aren’t meant to be disparaging or to say your solution is wrong. Just trying to help you understand the concepts behind what Unity is doing, so you can better implement what your doing now, as well as projects in the future.