Search code examples
c#unity-game-enginengui

Click Event Always getting only the last instantiated object (C# UNITY)


I know this maybe a duplicate of How to detect click/touch events on UI and GameObjects but I tried actually what's in there . But my problem still exists.

Here's my code

GameObject o = null;
private void Start()
{
    for (int i = 0; i < 6; i++)
    {
        o = Instantiate(obj) as GameObject;
        o.transform.SetParent(pos_obj);
        o.transform.localScale = Vector3.one;
        o.transform.name = "chips " + i;
       
        o.transform.localPosition = new Vector3(0, 0, 0);
        NGUITools.SetActive(o, true);

        UIGridReposition(UIGrid.Sorting.Vertical, true);
    }
}

This line of code above is how I instantiate my sprites and it is like this on my heirarchy

chips 1

chips 2

chips 3

chips 4

chips 5

Now when i try to put this line of code in the UI Button

public void TestClickEvent(){
   Debug.Log("This object is :" + o.transform.gameobject.name);
}

Now when I click on the Instantiated object only chips 5 will only be the output on my console. Even if i click the first,second etc Instantiated Object

Can someone please help me .

What I am trying to do is to get the designated number of each Intantiated Object for example

If i click chips 1 then it will output This object is : 1;


Solution

  • Found my solution instead of Camera.main I tried UICamera.currentCamera instead

    public void TestClickEvent()
    {
        Vector2 point = UICamera.currentCamera.ScreenToWorldPoint(Input.mousePosition);
        Ray ray = UICamera.currentCamera.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
    
        if (Physics.Raycast(ray, out hit, 100))
        {
            Debug.Log("I hit something :" + hit.collider.gameObject.name);
        }        
    }