单击事件总是只获取最后一个实例化的对象(C# UNITY)

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

我知道这可能是 的副本,但我实际尝试了其中的内容。但是我的问题依然存在。

这是我的代码

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

上面这行代码是我如何实例化我的精灵的,它在我的继承体系中是这样的

chips 1

chips 2

chips 3

chips 4

chips 5

现在,当我尝试将这行代码放入 UI Button

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

现在,当我单击实例化对象时,chips 5 只会在我的控制台上输出。即使我点击第一个,第二个等等 Instantiated Object

谁能帮我一下。

我想做的是获取每个Intantiated Object的指定数量,例如

如果我点击chips 1那么它会输出This object is : 1;

找到我的解决方案而不是 Camera.main 我尝试 UICamera.currentCamera 而不是

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

您正在使用 NGUI 并且检测点击事件的方式与您使用 Unity 的 UI 的方式完全不同。当检测到点击时,光线投射可能会起作用,但不是推荐的方法。始终为此使用回调事件。

您可以使用 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); 
}

对于 NGUI 确实没有明确的例子,所以希望通过大量的东西来完成一个简单的任务。