Hey everyone. This is the scenario. I have few game object in my 2d game with camera set to orthographic. Now I want to detect these game object when I left click on them and do certain thing for each of them. How can I go about that ?
The unity manual shows how to do this. Or you can try this (the first link is fine).
OnMouseOver()
{
//I don't think event keys workout side of GUI? Not sure enough to tell you but this is the code for that
i(Event.current.button == 1)
{
}
//Otherwise just get the input..
if(Input.MouseButtonDown(1) ) //1 is right mouse button
{
//Do whatever or run a method..
}
}
I tried OnMouseOver but I dont know how I can specify it on specific gameobject ?
I also saw the raycast method and gave it a try but i kept getting NullReferenceException on the code below
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.Log(ray);
}
}
any ideas ?
Okay I think I got it
Please share for the benefit of anyone searching for a similar solution.
OnMouseDown would work.
You’d apply the OnMouseOver Script onto each Gameobject. Since the OnMouseOver it specific to the Gameobject it is on.
OnMouseDown is too, isn’t it?
yes thats the way i did it as well. I was trying to make one script and put it in all game objects, but i couldnt manage to refer to all gameobject in that one script, So i end up making one script for each game object,
Void OnMouseOver()
{
if(Input.GetMouseButtonDown(0)
{
// Do this
}
}
OnMouseDown() should work the same way I assume but I havent tried it yet.