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

295 views Asked by At

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;

2

There are 2 answers

0
Ketskie On BEST ANSWER

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);
    }        
}
1
Programmer On

You're using NGUI and the way to detect click event is totally different than the way you would with Unity's UI. When detecting a click, a raycast may work but is not the recommend way to do so. Always use the callback events for that.

You can do this with UIEventListener.

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);

        UIEventListener.Get(o).onClick += TestClickEvent;

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

void TestClickEvent(GameObject sender) 
{ 
    Debug.Log("Clicked: " + sender.name); 
}

There is really no clear examples for NGUI out there so expect to go through a lot of stuff to complete a simple task.