CATCH MOUSE CLICK EVENT ON OBJECTS
Hi all,
First of all, as usual, im new to C# and Unity and trying to learn (this is the 2nd day :) ). I have googled and tried to use the codes but i wasnt able to successfully catch a mouse click on an object. Please help me with that. Here's it why i have and what i did.
I have a c# script where i create a list of objects in void start(),
void Start() {
for (int i = 0; i < numberofwords; i++)
{
GameObject go = new GameObject();
Transform tr = go.transform;
tr = Instantiate(word, new Vector3(10-((1+ i*3)), 2, 0), Quaternion.identity) as Transform;
words.Add(tr);
}
}
then in update i check if these are still visible and set their position and velocity as i need but this part is not relevant.
I have attached this script to MainCamera.
this part is working as i expect, but im not sure if im doing something fundamentally wrong.
Now, im trying to catch the click with following code in Update func;
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit,1000f))
{
Debug.Log("Hit at : " + hit.point);
}
} and i can catch the click and get its position but im not able to click on "Objects". I tried a few lines of code instead of Physics.Raycast but didnt work either.
Finally , I have box collider2d and rigidbody2d defined on my prefab.
Thanks in advance,
PS : Now i have added another object with Box Collider (Not 2d), and i was able to catch the click. So it seems i cant do it for 2d collider.
PS : Moderator , i found the solution, you can just reject this one :) When i tried to find something named RaycastHit2D and Ray2d i was able to find the following solution which works :
Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero);
if (hit.collider != null)
{
Debug.Log(hit.collider.name);
}